问:
Can the csv format be defined by a regex?
A colleague and I have recently argued over whether a pure regex is capable of fully encapsulating the csv format, such that it is capable of parsing all files with any given escape char, quote char, and separator char.

The regex need not be capable of changing these chars after creation, but it must not fail on any other edge case.

I have argued that this is impossible for just a tokenizer. The only regex that might be able to do this is a very complex PCRE style that moves beyond just tokenizing.

I am looking for something along the lines of:

... the csv format is a context free grammar and  as such, it is
  impossible to parse with regex alone ...

Or am I wrong? Is it possible to parse csv with just a POSIX regex?

For example, if both the escape char and the quote char are ", then these two lines are valid csv:

```<code>"""this is a test.""",""
"and he said,""What will be, will be."", to which I replied, ""Surely not!""","moving on to the next field here..."
</code>```

答:
Nice in theory, terrible in practice

By CSV I'm going to assume you mean the convention as described in RFC 4180.

While matching basic CSV data is trivial:

```<code>"data", "more data"
</code>```

Note: BTW, it's a lot more efficient to use a .split('/n').split('"') function for very simple and well-structured data like this. Regular Expressions work as a NDFSM (Non-Deterministic Finite State Machine) that wastes a lot of time backtracking once you start adding edge cases like escape chars.

For example here's the most comprehensive regular expression matching string I've found:

```<code>re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^                                   # Anchor to start of string.
\s*                                 # Allow whitespace before value.
(?:                                 # Group for value alternatives.
  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Allow whitespace after value.
(?:                                 # Zero or more additional values
  ,                                 # Values separated by a comma.
  \s*                               # Allow whitespace before value.
  (?:                               # Group for value alternatives.
    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,
  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,
  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.
  )                                 # End group of value alternatives.
  \s*                               # Allow whitespace after value.
)*                                  # Zero or more additional values
$                                   # Anchor to end of string.
"""
</code>```

It reasonably handles single and double quoted values, but not newlines in values, escaped quotes, etc.

Source: Stack Overflow - How can I parse a string with JavaScript

It's becomes a nightmare once the common edge-cases are introduced like...

```<code>"such as ""escaped""","data"
"values that contain /n newline chars",""
"escaped, commas, like",",these"
"un-delimited data like", this
"","empty values"
"empty trailing values",        // <- this is completely valid
                                // <- trailing newline, may or may not be included
</code>```

The newline-as-value edge case alone is enough to break 99.9999% of the RegEx based parsers found in the wild. The only 'reasonable' alternative is to use RegEx matching for basic control/non-control character (ie terminal vs non-terminal) tokenization paired with a state machine used for higher level analysis.

Source: Experience otherwise known as extensive pain and suffering.

I am the author of jquery-CSV, the only javascript based, fully RFC-compliant, CSV parser in the world. I have spent months tackling this problem, speaking with many intelligent people, and trying a ton if different implementations including 3 full rewrites of the core parser engine.

tl;dr - Moral of the story, PCRE alone sucks for parsing anything but the most simple and strict regular (Ie Type-III) grammars. Albeit, it's useful for tokenizing terminal and non-terminal strings.

Body:
Nice in theory, terrible in practice

By CSV I'm going to assume you mean the convention as described in RFC 4180.

While matching basic CSV data is trivial:

"data", "more data"

Note: BTW, it's a lot more efficient to use a .split('/n').split('"') function for very simple and well-structured data like this. Regular Expressions work as a NDFSM (Non-Deterministic Finite State Machine) that wastes a lot of time backtracking once you start adding edge cases like escape chars.

For example here's the most comprehensive regular expression matching string I've found:

re_valid = r"""
# Validate a CSV string having single, double or un-quoted values.
^                                   # Anchor to start of string.
\s*                                 # Allow whitespace before value.
(?:                                 # Group for value alternatives.
  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,
| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,
| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.
)                                   # End group of value alternatives.
\s*                                 # Allow whitespace after value.
(?:                                 # Zero or more additional values
  ,                                 # Values separated by a comma.
  \s*                               # Allow whitespace before value.
  (?:                               # Group for value alternatives.
    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,
  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,
  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.
  )                                 # End group of value alternatives.
  \s*                               # Allow whitespace after value.
)*                                  # Zero or more additional values
$                                   # Anchor to end of string.
"""

It reasonably handles single and double quoted values, but not newlines in values, escaped quotes, etc.

Source: Stack Overflow - How can I parse a string with JavaScript

It's becomes a nightmare once the common edge-cases are introduced like...

"such as ""escaped""","data"
"values that contain /n newline chars",""
"escaped, commas, like",",these"
"un-delimited data like", this
"","empty values"
"empty trailing values",        // <- this is completely valid
                                // <- trailing newline, may or may not be included

The newline-as-value edge case alone is enough to break 99.9999% of the RegEx based parsers found in the wild. The only 'reasonable' alternative is to use RegEx matching for basic control/non-control character (ie terminal vs non-terminal) tokenization paired with a state machine used for higher level analysis.

Source: Experience otherwise known as extensive pain and suffering.

I am the author of jquery-CSV, the only javascript based, fully RFC-compliant, CSV parser in the world. I have spent months tackling this problem, speaking with many intelligent people, and trying a ton if different implementations including 3 full rewrites of the core parser engine.

tl;dr - Moral of the story, PCRE alone sucks for parsing anything but the most simple and strict regular (Ie Type-III) grammars. Albeit, it's useful for tokenizing terminal and non-terminal strings.


问:
Why do programming languages allow shadowing/hiding of variables and functions?
Many of the most popular programming languges (such as C++, Java, Python etc.) have the concept of hiding / shadowing of variables or functions. When I've encountered hiding or shadowing they have been the cause of hard to find bugs and I've never seen a case where I found it necessary to use these features of the languages.

To me it would seem better to disallow hiding and shadowing.

Does anybody know of a good use of these concepts?

Update:

I'm not refering to encapsulation of class members (private/protected members).

答:
Honestly, Eric Lippert, the principle developer on the C# compiler team, explains it pretty well (thanks Lescai Ionel for the link). .NET's IEnumerable and IEnumerable<T> interfaces are good examples of when member hiding is useful.

In the early days of .NET, we didn't have generics. So the IEnumerable interface looked like this:

```<code>public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
</code>```

This interface is what allowed us to foreach over a collection of objects, however we had to cast all those objects in order to use them properly.

Then came generics. When we got generics, we also got a new interface:

```<code>public interface IEnumerable<T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}
</code>```

Now we don't have to cast objects while we're iterating through them! Woot! Now, if member hiding was not allowed, the interface would have to look something like this:

```<code>public interface IEnumerable<T> : IEnumerable
{
    IEnumerator<T> GetEnumeratorGeneric();
}
</code>```

This would be kind of silly, because GetEnumerator() and GetEnumeratorGeneric() in both cases do pretty much exactly the same thing, but they have slightly different return values. They are so similar, in fact, that you pretty much always want to default to the generic form of GetEnumerator, unless you're working with legacy code that was written before generics were introduced into .NET.

Sometimes member hiding does allow more room for nasty code and difficult-to-find bugs. However sometimes it's useful, such as when you want to change a return type without breaking legacy code. That's just one of those decisions language designers have to make: Do we inconvenience the developers who legitimately need this feature and leave it out, or do we include this feature into the language and catch flak from those who are victims of its misuse?

ContentLicense: CC BY-SA 3.0

Body:
Honestly, Eric Lippert, the principle developer on the C# compiler team, explains it pretty well (thanks Lescai Ionel for the link). .NET's IEnumerable and IEnumerable<T> interfaces are good examples of when member hiding is useful.

In the early days of .NET, we didn't have generics. So the IEnumerable interface looked like this:

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}

This interface is what allowed us to foreach over a collection of objects, however we had to cast all those objects in order to use them properly.

Then came generics. When we got generics, we also got a new interface:

public interface IEnumerable<T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

Now we don't have to cast objects while we're iterating through them! Woot! Now, if member hiding was not allowed, the interface would have to look something like this:

public interface IEnumerable<T> : IEnumerable
{
    IEnumerator<T> GetEnumeratorGeneric();
}

This would be kind of silly, because GetEnumerator() and GetEnumeratorGeneric() in both cases do pretty much exactly the same thing, but they have slightly different return values. They are so similar, in fact, that you pretty much always want to default to the generic form of GetEnumerator, unless you're working with legacy code that was written before generics were introduced into .NET.

Sometimes member hiding does allow more room for nasty code and difficult-to-find bugs. However sometimes it's useful, such as when you want to change a return type without breaking legacy code. That's just one of those decisions language designers have to make: Do we inconvenience the developers who legitimately need this feature and leave it out, or do we include this feature into the language and catch flak from those who are victims of its misuse?

ContentLicense: CC BY-SA 4.0


问:
When should I increment version number?
I didn't learn programming at school and I do not work as a (professional) developer, hence a lot of basics are not quite clear to me. This question tries to clarify one of them.

Now let's suppose that I have issues #1, #2 and #3 in my Issues Tracker that are set to be corrected/enhanced for version 1.0.0 and that the last (stable) version is 0.9.0.

When should I increment to version 1.0.0 ? When a) just one of the listed above issues is closed or b) when all the issues related to version 1.0 are closed ?

Which one is the right way to do it ? And by the right way, I mean what is currently used in the industry.

答:
For continuiously deployed web applications, we tend to construct build numbers using symver up front and a build number tailing, ie: 2.5.3.4328 where 4328 comes from the continuious integration system. General expectation is that numbers change by deliberate steps but that the build number is the true unique ID.

What it seems to be doing here is capturing the day of deployment and the related svn build number:

```<code>        <div id="svnrev">
            rev 2013.10.21.1078
        </div>
</code>```

For what it's worth.

Title: When should I increment version number?

Body:
For continuiously deployed web applications, we tend to construct build numbers using symver up front and a build number tailing, ie: 2.5.3.4328 where 4328 comes from the continuious integration system. General expectation is that numbers change by deliberate steps but that the build number is the true unique ID.

What it seems to be doing here is capturing the day of deployment and the related svn build number:

        <div id="svnrev">
            rev 2013.10.21.1078
        </div>

For what it's worth.


问:
Best way to store motion changes to reduce memory
I am comparing jpeg to jpeg in a constant 'video-stream'. I am using EMGU/OpenCV to compare each pixels at the byte level. There are 3 channels to each image (RGB). I have heard that it is common practice to store only the pixels that have changed between frames as a way of conserving memory space. But, if for instance, I say EVERY pixel has changed (Please note I am using an exaggerated example to make my point and I would normally discard such large changes.) then the resultant bytes saved is 3 times larger than the original jpeg.

How can I store such motion changes efficiently?

答:
From what I remember, the JPEG and MPEG/H264 family of motion codecs internally represent the images in YCbCr colorspace (not RGB), where Y is the luminance, and Cb with Cr are the chrominance components. While every pixel of Y component is used, the chrominance is downsampled according to one of a few possible schemes. The main compression gain in JPEG (and keyframes of motion codecs) is achieved by quantization of DCT results, which means throwing away the high frequency components of each image block.
To compress the differences between frames caused by motion, the motion prediction is used in the luminance component (before DCT). Very briefly, each frame is divided into regular blocks of pixels, and each block of current frame is compared with pixels of the previous frame to find the closest match. This produces the deplacement vector (motion vector). Because the match is not ideal, the pixel value differences in each of the Y, Cb, and Cr components are passed through the normal JPEG compression (DCT, quantization, Huffman encoding) and sent along the motion vector to form a Delta Frame.

Here, you will find a few hints for your further research. I hope you'll not have to reinvent the wheel. There are some Linux/Unix image processing tools you might harness for your task.


问:
How to safely run random binary codes?
Okay, so I am looking for a way to safely run a randomly generated binary code. I also need to be able to decompile the code. Any ideas and all programming languages are welcome. </p>

<p>BTW it most be binary code; byte code or source code will not work. This is a research project, so I can't go adding variables.       </p>

答:
From the looks of it, you want to do something similar to what malware researchers do for malware analysis.

As far as safely running your random binaries, FrustratedWithFormsDesigner's comment covers it well.

Just run it on a virtual machine to keep any risk from spilling into your computer. There are lots of free virtual machine out there like Virtual Box or some free tier of VMWare or Parallels

But if you want to know more about how to confine or sandbox the binaries, you can also read more here: http://www.porcupine.org/forensics/forensic-discovery/chapter6.html

As for decompiling, there is also some mention of that in the previous article. You can also look-up reverse engineering which might help.

Though just out of curiosity, do you mind if I ask what is the research project about? Forensics or Reverse Engineering or ???

Title: How to safely run random binary codes?


问:
What is the difference between WCF service and a simple Web service in developing using .NET Framework?
My questions are:

What is the difference between WCF service and a simple Web service in .NET Framework?

What a WCF Service can do which a .NET Web service cant? In other words, what are the limitation of .NET Web services which were overcome in WCF services?

I understand that WCF are REST based and .NET web services are SOAP based. But I need to know more than that. How a developer will make a design decision whether to developer a Web service or a WCF service?

答:
Here is the basic difference between the two -

1 File Format/Extension :

i) ASP.net service - '.asmx'

ii) WCF service - '.svc'

2 Hosting :

i) ASP.net service - Can be hosted in IIS also can be hosted in a Windows Service.

ii) WCF service - Very flexible, can be hosted in IIS, Windows Activation Services(WAS), Managed Windows Services and It also supports Self-Hosting.

3 Transport Protocols/Binding :

i) ASP.net service - It supports HTTP & TCP protocols along with custom binding.

ii) WCF service - supports HTTP, WS-HTTP, TCP, Custom, Named Pipes, MSMQ & P2P(Point to Point) etc.

4 Data Transformation :

i) ASP.net service - XML serializer for Data Transformation.

ii) WCF service - DataContractSerializer for Data Transformation.

5 Serialization NameSpace :

i) ASP.net service - System.XML.Serialization

ii) WCF service - System.RunTime.Serialization

6 Supported Operations :

i) ASP.net service - only One-Way and Request-Response type.

ii) WCF service - Includes One-Way, Request-Response and Duplex.

7 Encoding :

i) ASP.net service - It uses following encoding mechanisms -
XML1.0, MTOM (Message Transmission Optimization Mechanism), DIME (Direct Internet Message Encapsulation)

ii) WCF service - It uses following encoding mechanisms -
XML1.0, MTOM, Binary

Read more differences - http://www.csharptutorial.in/2012/01/cnet-difference-between-web-service-and.html


答:
I can tell you how I do it at work.

We have a continuous integration server that builds, tests, tags and outputs a versioned package.  We only proceed to the next stage if the previous one is %100 successful.

Our version looks like this:  <Major Version>.<Minor Version>.<Build Number>

Every successful build that has no completed bug fix or feature enhancement increments the Build Number.

Every successful build with a completed bug fix or feature enhancement increments the Minor Version.  This is automatically detected by the presence of a commit message using a particular format.  This commit message also automatically get's pulled into the projects ChangeLog.

Every Major Version increment is done by hand when we have non backward compatible changes, rewrites from scratch or other reasons made on a case by case basis.

Title: When should I increment version number?

Body:
I didn't learn programming at school and I do not work as a (professional) developer, hence a lot of basics are not quite clear to me. This question tries to clarify one of them.

Now let's suppose that I have issues #1, #2 and #3 in my Issues Tracker that are set to be corrected/enhanced for version 1.0.0 and that the last (stable) version is 0.9.0.

When should I increment to version 1.0.0 ? When a) just one of the listed above issues is closed or b) when all the issues related to version 1.0 are closed ?

Which one is the right way to do it ? And by the right way, I mean what is currently used in the industry.


问:
Handling changes to data types and entries in a database migration
I'm fully redesigning a site that indexes a number of articles with basic search functionality.  The previous site was written about a decade ago, and I'm salvaging about 30,000 entries with data stored in less-than-ideal formats.  While I'm moving from MSSQL to MySQL, I don't need to make any "live" changes, so this is not a production-level migration issue so much as a redesign.

For instance, dates are stored the same as tags/subjects about the articles, but in strings as "YYYYMMDDd" (the lowercase d stands for "date" in the string).  Essentially, before or after I move from the previous database format to a new one, I'm going to need to do a lot of replacement of individual entries.  While I understand how to do operations with regular expressions in non-database issues, my database experience isn't robust enough to know the best way to handle this.

What is the best (or standard) way to handle major changes like this?  Is there an SQL operation I should be looking into?  Please let me know if the problem isn't clear--I'm not entirely sure what kind of answer I'm looking for.

答:
One way which I can see to handle this case is (though it might not be ideal way):

Write MS SQl query to fetch data in form which can be imported into MySql db like changing date from string to proper date

Store above result in file

Write MySql query to directly store data from file to database


问:
ASP.NET Web Forms is bad, or what am I missing?
Being a PHP guy myself I recently had to write a spider to an asp.net site. I was really surprised by the different approach to ajax and form-handling.

For example, in the PHP sites I've worked with, a deletion of a database entry would be something like:
```GET delete.php?id=&confirm=yes``` and get a "success" back in some form (in the ajax case, probably a json reply).

In this asp.net application you would instead post a form, including all inputs on the page, with a huge __VIEWSTATE and __EVENTVALIDATION. This would be more than 10 times as big as above.

The reply would be the complete side again, with a footer containing some structured data for javascript to parse and display the result. Again, the whole page is sent, and then throwed away(?) since it's already displayed. Why not just send the footer with the data to parse (it's not json nor xml but a | separated list).

I really can't see why you would design a system that way. Usually you've a fast client, and a somewhat fast server but a really slow connection. Why not keep the datatransfer to a minimum? Why those huge __VIEWSTATE and __EVENTVALIDATION?

It seems that everything is done way to chatty and way to complicated. I really can't see the point and that usually means that I'm missing something. So please tell me, what are the reasons for this design and what benefits (and weaknesses) does it have?

(Yes I know that __VIEWSTATE is used to tell what type of form-konfiguration should be sent back to the server. But WHY is this needed?)

Please keep this discussion strictly technical and avoid flamewars.

Update:

Please excuse the somewhat rantish question. I tried to explain my view to be able to get a better answer. I am not saying that asp.net is bad, I am saying that I don't understand the meaning of those concepts. Usually that means that I've things to learn instead of the concepts beeing wrong.

I appreciate the explanations about that "you don't have to do this way in asp.net", I'll read up on MVC and other .net technologies. However, there most be a reason for this site (the one I referred to) to be written the way it is. It's written by professionals for a big organisation with far more experience than what I've. Any explanation about their (possible) design choice would be welcome.

答:
Please keep this discussion strictly technical and avoid flamewars.

We'll see ;) (As Bart van Ingen Schenau points out, your question is a little ranty, which may not help the situation)

You're actually referring to ASP.NET Webforms. ASP.NET doesn't suck at all; MVC is great (and doesn't share the problem you mention).

You're right that the ViewState is large and seems like a nuisance to work with. In a way it can be for developers too. Why was it developed this way? Well it can be useful - I suspect particularly for developers coming from Winforms; the web behaves fundamentally differently from desktop applications but Microsoft tried to mimic the behaviour with abstractions like the ViewState (a big object to keep track of where everything is at). The large Viewstate being passed around is also less of an issue with things like Intranets (where Webforms may be fairly common).

A great discussion and comparison of the two is answered in this question: When to favor ASP.NET WebForms over MVC. Why it was designed this way is also mentioned.


问:
REST partial bad request
I'm implementing a REST method that allows you to post a list of items. If all data is correct I obviously return a 201 and if all data is incorrect a 400.

What would be an appropriate response code if some items are correct and others are not?

答: If you are willing to step slightly outside pure HTTP responses, you could go the same way as the WebDAV protocol has done. They have extended the HTTP protocol with, among other things, a "multi-status response" (using code 207), that contains a status response for each individual item in its body.</p>

Title: REST partial bad request


问:
Should I just always Convert.ToInt32 my integers to account for potential nullable integers?
If my MSSQL database contains a data type that is NULL (i.e. null is allowed) then ORMs, such as EntityFramework in my case, create .NET objects that are nullable.

This is great, and the way I use nullables is like this:

C#

```<code>int? someInt = 5;

int newInt = someInt.Value; // woot
</code>```

VB.NET

```<code>Dim someInt As Integer?

Dim newInt As Integer = someInt.Value ' hooray
</code>```

However, recently I had to make a change to the database to make an Id field no longer NULL (nullable). This means that .Value is now broken. This is a nuisance if the Id property is used a lot.

One solution that I thought of is to just use Convert.ToInt32 on Id fields so it doesn't matter if an int is nullable or not.

C#

```<code>int newInt = Convert.ToInt32(someInt); // always compiles
</code>```

VB.NET

```<code>Dim newInt As Integer = Convert.ToInt32(someInt) ' always compiles
</code>```

Is this a bad approach and are there any alternatives?

答:
Well, first off, if a field is nullable, that means it may not have a value.  Ints always have a value.  If you must for some reason fake a value, then use someNullable.GetValueOrDefault() (which btw, allows a parameter to define the default value).

Secondly, the right thing to do when something goes from sometimes having a value to always having a value, is to refactor it as necessary to represent this new behavior.

Your fundamental problem is that you are trying to treat two entirely seperate scenarios as being the same - one way or another you are probably failing to properly model what is taking place.


答:
Webforms was designed in a time when people wanted web applications to look like windows applications. This was a dark time on the internet where developers were forced to learn page lifecycles and deal with horrible view states and 3rd party controls which would cause such bloat the very fabric of the internet would be shaken...

That is Webforms, an archaic technology that is better left forgotten, and people who say otherwise should also be forgotten.

Like another answer says, MVC is the latest way from MS (although it was pretty much just spawned from Ruby on Rails I think) to design good websites.

Anyway the "Why is MVC great" is another topic, but for this one the answer is.

YES WEBFORMS IS AWFUL DO NOT USE IT FOR NEW PROJECTS

Title: ASP.NET Web Forms is bad, or what am I missing?

Body:
Being a PHP guy myself I recently had to write a spider to an asp.net site. I was really surprised by the different approach to ajax and form-handling.

For example, in the PHP sites I've worked with, a deletion of a database entry would be something like:
```GET delete.php?id=&confirm=yes``` and get a "success" back in some form (in the ajax case, probably a json reply).

In this asp.net application you would instead post a form, including all inputs on the page, with a huge __VIEWSTATE and __EVENTVALIDATION. This would be more than 10 times as big as above.

The reply would be the complete side again, with a footer containing some structured data for javascript to parse and display the result. Again, the whole page is sent, and then throwed away(?) since it's already displayed. Why not just send the footer with the data to parse (it's not json nor xml but a | separated list).

I really can't see why you would design a system that way. Usually you've a fast client, and a somewhat fast server but a really slow connection. Why not keep the datatransfer to a minimum? Why those huge __VIEWSTATE and __EVENTVALIDATION?

It seems that everything is done way to chatty and way to complicated. I really can't see the point and that usually means that I'm missing something. So please tell me, what are the reasons for this design and what benefits (and weaknesses) does it have?

(Yes I know that __VIEWSTATE is used to tell what type of form-konfiguration should be sent back to the server. But WHY is this needed?)

Please keep this discussion strictly technical and avoid flamewars.

Update:

Please excuse the somewhat rantish question. I tried to explain my view to be able to get a better answer. I am not saying that asp.net is bad, I am saying that I don't understand the meaning of those concepts. Usually that means that I've things to learn instead of the concepts beeing wrong.

I appreciate the explanations about that "you don't have to do this way in asp.net", I'll read up on MVC and other .net technologies. However, there most be a reason for this site (the one I referred to) to be written the way it is. It's written by professionals for a big organisation with far more experience than what I've. Any explanation about their (possible) design choice would be welcome.


答:
Your question could be read two ways: either you're asking about variable/function scope in general, or you're asking a more specific question about scope in an inheritance hierarchy.  You didn't mention inheritance specifically, but you did mention hard to find bugs, which sounds more like scope in the context of inheritance than plain scope, so I'll answer both questions.

Scope in general is a good idea, because it allows us to focus our attention on one specific (hopefully small) portion of the program.  Because it lets local names always win, if you read only the portion of the program that's in a given scope, then you know exactly what parts were defined locally and what was defined elsewhere.  Either the name refers to something local, in which case the code that defines it is right in front of you, or it's a reference to something outside the local scope.  If there aren't any non-local references that could change out from under us (especially global variables, which could be changed from anywhere), then we can evaluate whether the part of the program in the local scope is correct or not without referring to any part of the rest of the program at all.

It may possibly occasionally lead to a few bugs, but it more than compensates by preventing an enormous amount of otherwise possible bugs.  Other than making a local definition with the same name as a library function (don't do that), I can't see an easy way to introduce bugs with local scope, but local scope is what lets many parts of the same program use i as the index counter for a loop without clobbering each other, and lets Fred down the hall write a function that uses a string named str that won't clobber your string with the same name.

I found an interesting article by Bertrand Meyer that discusses overloading in the context of inheritance.  He brings up an interesting distinction, between what he calls syntactic overloading (meaning that there are two different things with the same name) and semantic overloading (meaning that there are two different implementations of the same abstract idea).  Semantic overloading would be fine, since you meant to implement it differently in the subclass; syntactic overloading would be the accidental name collision that caused a bug.

The difference between overloading in an inheritance situation which is intended and which is a bug is semantics (the meaning), so the compiler has no way of knowing whether what you did is right or wrong.  In a plain scope situation, the right answer is always the local thing, so the compiler can figure out what the right thing is.

Bertrand Meyer's suggestion would be to use a language like Eiffel, which doesn't allow name clashes like this and forces the programmer to rename one or both, thus avoiding the problem entirely.  My suggestion would be to avoid using inheritance entirely, also avoiding the problem entirely.  If you can't or don't want to do either of those things, there are still things you can to to reduce the probability of having a problem with inheritance: follow the LSP (Liskov Substitution Principle), prefer composition over inheritance, keep your inheritance hierarchies shallow, and keep the classes in an inheritance hierarchy small.  Also, some languages may be able to issue a warning, even if they wouldn't issue an error, as a language like Eiffel would.

Title: Why do programming languages allow shadowing/hiding of variables and functions?

Body:
Many of the most popular programming languges (such as C++, Java, Python etc.) have the concept of hiding / shadowing of variables or functions. When I've encountered hiding or shadowing they have been the cause of hard to find bugs and I've never seen a case where I found it necessary to use these features of the languages.

To me it would seem better to disallow hiding and shadowing.

Does anybody know of a good use of these concepts?

Update:

I'm not refering to encapsulation of class members (private/protected members).


问:
The better way to ask for input?
I am wondering which is the best way to go with java code. I need to create a class with simple prompts for input.. I have tried using both classes and cannot work out the particular benefits for each. Is this because I am still in the early stages of programming or are there situations that will occur as it becomes more complex??

```<code>import java.util.Scanner;

public class myClass
{
    Scanner stdin = new Scanner(System.in);

    public String getInput(String prompt)
    {
        System.out.print(prompt);
        return stdin.nextLine();
    }

}
</code>```

... or

```<code>import java.io.*;

public class myClass
{
    public static void main(String[] args) throws IOException
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Input something: ");
        String name = stdin.readLine();
    }
}
</code>```

I know these examples are showing different methods within these classes, but thought this might serve well for the discussion.

I'm really not sure which site is the best to ask this on.

答:
I've been a Java programmer for 6 years now, and I rarely have to worry about how to read input from the command line.  Most times, when I'm dealing with input and output, they are usually streams of some sort and therefore using a BufferedReader is generally a best practice, since it takes the bottleneck off having to read a file line by line.

However, for what you're out to do, using System.in with Scanner is perfectly fine.  Lets just say that if I wanted to handle large amounts of input, perhaps I would wrap System.in with a BufferedInputStream for efficiency, but if your program is waiting on you, then there is no advantage gained.

Title: The better way to ask for input?


问:
Algorithm to infer tag hierarchy
I'm looking for an algorithm to infer a hierarchy from a set of tagged items.

E.g. if the following items have the tags:

```<code>1 a
2 a,b
3 a,c
4 a,c,e
5 a,b
6 a,c
7 d
8 d,f
</code>```

Then I can construct an undirected graph (or graphs) by tallying the node weights and edge weights:

```<code> node weights  edge weights

 a 6           a-b 2
 b 2           a-c 3
 c 3           c-e 1
 d 2           a-e 1  <-- this edge is parallel to a-c and c-e and not wanted
 e 1           d-f 1
 f 1
</code>```

The first problem is how to drop any redundant edges to get to the simplified graph? Note that it's only appropriate to remove that redundant a-e edge in this case because something is tagged as a-c-e, if that wasn't the case and the tag was a-e, that edge would have to remain. I suspect that means the removal of edges can only happen during the construction of the graph, not after everything has been tallied up.

What I'd then like to do is identify the direction of the edges to create a directed graph (or graphs) and pick out root nodes to hopefully create a tree (or trees):

```<code> trees

    a        d
  // \\      |
 b     c     f
        \
         e
</code>```

It seems like it could be a string algorithm - longest common subsequences/prefixes - or a tree/graph algorithm, but I am a little stuck since I don't know the correct terminology to search for it.

答:
This is what I've come up with. For my data, it's fast enough and the results are what I was after.

First, construct a tree where nodes are not necessarily unique, all nodes must share a "root" tag (in this case 'a') so partition returns just one tree, in pseudo-python:

```<code>nodes = [[a,b], [a,c], [a,b,d], [a,b,d,e], [a,c,e], [a,c,d,e]]

tree = partition(nodes)[0]

def partition(self, nodes, parent=None):
    children = []
    while nodes:
        pivot, count = most_frequent_tag(nodes)
        if not pivot:
            break

        left = [node for node in nodes if pivot in node]
        right = [node for node in nodes if pivot not in node]
        child = Node(pivot, count, parent=parent)
        child.children = partition([[tag for tag in node if tag != pivot]
                                    for node in left],
                                   parent=child)
        children.append(child)
        nodes = right
    return children

def most_frequent_tag(nodes):
    ...
    return tag, count

class Node(object):
    def __init__(self, tag, count, parent=None):
        self.tag = tag
        self.count = count
        self.parent = parent
        self.children = []
</code>```

This results in the tree:

```<code>   a (6)
  /    \
b (3)  c (3)
 |      |
d (2)  e (2)
 |      |
e (1)  d (1)
</code>```

The nodes in this tree have to be reordered for it to turn into an acyclic graph, so swap any parent-child relationships where the child occurs more frequently than the parent (any metric will do though). When they have the same frequency, ensure the parent has the lower tag (alphabetically).

This is a little tricky as the parent node may have to be split if it's count > than the child count.

```<code>tree.check_order()

def Node.check_order(self):
    new_children = []
    for child in self.children:
        swaps.extend(child.check_order())
        if not self.in_order(child):
            # add child to parent, self to child
            new_child = Node(child.tag, child.count, self.parent)
            new_self = Node(self.tag, child.count, new_child)
            self.count -= child.count
            new_self.children = child.children
            new_child.children.append(new_self)
            self.parent.children.append(new_child)
        else:
            new_children.append(child)
    self.children = new_children
</code>```

The new tree now looks like:

```<code>      a (6)
     /    \
   b (3)   c (3)
  /    \     \
d (2)  e (1)  e (2)
        |      |
       d (1)  d (1)
</code>```

Once that's complete, the tree can be traversed to create a list of graph edges (there may be some duplicates) or a co-occurrence matrix.

Title: Algorithm to infer tag hierarchy

Body:
This is what I've come up with. For my data, it's fast enough and the results are what I was after.

First, construct a tree where nodes are not necessarily unique, all nodes must share a "root" tag (in this case 'a') so partition returns just one tree, in pseudo-python:

nodes = [[a,b], [a,c], [a,b,d], [a,b,d,e], [a,c,e], [a,c,d,e]]

tree = partition(nodes)[0]

def partition(self, nodes, parent=None):
    children = []
    while nodes:
        pivot, count = most_frequent_tag(nodes)
        if not pivot:
            break

        left = [node for node in nodes if pivot in node]
        right = [node for node in nodes if pivot not in node]
        child = Node(pivot, count, parent=parent)
        child.children = partition([[tag for tag in node if tag != pivot]
                                    for node in left],
                                   parent=child)
        children.append(child)
        nodes = right
    return children

def most_frequent_tag(nodes):
    ...
    return tag, count

class Node(object):
    def __init__(self, tag, count, parent=None):
        self.tag = tag
        self.count = count
        self.parent = parent
        self.children = []

This results in the tree:

   a (6)
  /    \
b (3)  c (3)
 |      |
d (2)  e (2)
 |      |
e (1)  d (1)

The nodes in this tree have to be reordered for it to turn into an acyclic graph, so swap any parent-child relationships where the child occurs more frequently than the parent (any metric will do though). When they have the same frequency, ensure the parent has the lower tag (alphabetically).

This is a little tricky as the parent node may have to be split if it's count > than the child count.

tree.check_order()

def Node.check_order(self):
    new_children = []
    for child in self.children:
        swaps.extend(child.check_order())
        if not self.in_order(child):
            # add child to parent, self to child
            new_child = Node(child.tag, child.count, self.parent)
            new_self = Node(self.tag, child.count, new_child)
            self.count -= child.count
            new_self.children = child.children
            new_child.children.append(new_self)
            self.parent.children.append(new_child)
        else:
            new_children.append(child)
    self.children = new_children

The new tree now looks like:

      a (6)
     /    \
   b (3)   c (3)
  /    \     \
d (2)  e (1)  e (2)
        |      |
       d (1)  d (1)

Once that's complete, the tree can be traversed to create a list of graph edges (there may be some duplicates) or a co-occurrence matrix.


问:
Principles of an extensible data proxy
There is a growing industry now with more than 30 companies playing in the Backend-As-A-Service (BaaS) market.

The principle is simple: give companies a secure way of exposing data housed on premises and behind the firewall publicly.

This can include database data, as well as Legacy PC data through established connectors; SAP for example provides a connector for transacting with their legacy systems.

Early attempts were fixed providers for specific systems like SAP, IBM or Oracle, but the new breed is extensible, allowing Channel Partners and Consultants to build robust integration applications that can consume whatever data sources the client wants to expose.

I just happen to be close to finishing a Cloud Based HTML5 application platform that provides robust integration services, and I would like to break ground on an extensible data proxy to complete the system.

From what I can gather, I need to provide either an installable web service of some kind, or a Cloud service which the client can configure with VPN for interactions.

Then I can build in connectors, which can be activated with a service account, and expose those transactions via web services of some kind (JSON, SOAP, etc).

I can also provide a framework that allows people to build in their own connectors, and use some kind of schema to hook those connectors into the proxy.

The end result is some kind of public facing web service that could securely be consumed by applications to show data through HTML5 on any device.

My gut is, this isn't as hard as it sounds. Almost all of the 30+ companies (With more popping up almost weekly) have all come into existence in the last 18 months or so, which tells me either the root technology, or the skillset to create the technology is in abundance right now.

Where should I start on this? Are there some open source projects I can leverage? A specific group of developers I can hire? I'm confident someone here can set me on the right path and save me some time.

You don't see this many companies spring up this rapidly if they are all starting from scratch with proprietary technology.

The Register: WTF is BaaS

One Minute Video from Kony on their BaaS

答:
The principle is simple: give companies a secure way of exposing data housed on premises and behind the firewall publicly.

From the definition of Back end as a Service in one of this article that you mentioned

```<code>a backend-as-a-service gives you an API into a common
infrastructure for sending data between applications
</code>```

So in principle, BaaS is simply providing APIs to allow applications to communicate with each other. Not necessarily restricted to items behind corporate firewalls but even items available publicly, look at firebase for example. Firebase doesn't do the authentication of users, another part of your app does that. What firebase does do is to provide your application with an api for real time communication with other instances of your application as well as a real-time database storage service.

The end result is some kind of public facing web service that could securely be consumed by applications to show data through HTML5 on any device. My gut is, this isn't as hard as it sounds.

The difficulty lies on what kind of communication to what kind of things will you be offering and how general purpose or specialized it is. In Meteor's case, it doesn't seem too complicated to do what its doing, very well defined and specialized to connections with other social media/social network apis. In Firebase' case, they had to make a general purpose real time communication API from ground up(though they heavily made use of nodejs), that should speak for itself.

Ok, so back to your question.

Where should I start on this?

You could start by defining the specifics of your BaaS. Specifically, what kind of communication are you offering. Who will communicate with who, communication security etc.

Are there some open source projects I can leverage?

Open source projects? Sadly, I got none.

A specific group of developers I can hire?

I believe API developers would be a good fit here. They should be able to create ways for your end points to communicate with each other for the sake of your BaaS

Title: Principles of an extensible data proxy

Body:
The principle is simple: give companies a secure way of exposing data housed on premises and behind the firewall publicly.

From the definition of Back end as a Service in one of this article that you mentioned

a backend-as-a-service gives you an API into a common
infrastructure for sending data between applications

So in principle, BaaS is simply providing APIs to allow applications to communicate with each other. Not necessarily restricted to items behind corporate firewalls but even items available publicly, look at firebase for example. Firebase doesn't do the authentication of users, another part of your app does that. What firebase does do is to provide your application with an api for real time communication with other instances of your application as well as a real-time database storage service.

The end result is some kind of public facing web service that could securely be consumed by applications to show data through HTML5 on any device. My gut is, this isn't as hard as it sounds.

The difficulty lies on what kind of communication to what kind of things will you be offering and how general purpose or specialized it is. In Meteor's case, it doesn't seem too complicated to do what its doing, very well defined and specialized to connections with other social media/social network apis. In Firebase' case, they had to make a general purpose real time communication API from ground up(though they heavily made use of nodejs), that should speak for itself.

Ok, so back to your question.

Where should I start on this?

You could start by defining the specifics of your BaaS. Specifically, what kind of communication are you offering. Who will communicate with who, communication security etc.

Are there some open source projects I can leverage?

Open source projects? Sadly, I got none.

A specific group of developers I can hire?

I believe API developers would be a good fit here. They should be able to create ways for your end points to communicate with each other for the sake of your BaaS


问:
How can a single database work for website, mobile apps?
We have developed a job-portal where users can view jobs and and also post jobs. We have used Php and MySQL. We hosted this on web faction. Now we want to develop the mobile app of the job portal for android, ios and windows. As the database should be synchronous and aligned dynamically with apps and website database. As the back-end code has to be changed to Java in android and c# in windows, how to manage a single synchronous database?</p>

答:
You need to make your php based web application 'service-oriented', i.e. it acts as a web service endpoint and only processes requests and responds with XML/JSON/text data. This interface will be available for use to both your mobile application and your web application (use ajax to communicate with the service).

In this case your web-application and mobile-application act as presentation layer for the data received from the web-service. However, because of how crawlers parse web sites, your ajax based web-application will not be readable by them. If you need your web-application to be readable by the crawlers then you need to introduce another layer that interacts with the web-service and presents the information as general HTML based page.

So your web app will be like:

```<code>Client >> Presentation-Layer (js) >[HTTP]> Service-Layer (php) >> DB (MySQL)
</code>```

Or,

```<code>Client >[HTTP]> Presentation-Layer (php) >[HTTP]> Service-Layer (php) >> DB (MySQL)
</code>```

if you want it to be parsable by crawlers.

And your mobile app will be like:

```<code>Client >> Presentation-Layer (java/obj-C) >[HTTP]> Service-Layer >> DB (MySQL)
</code>```

You can also connect remotely to your main database from both the web application as well as the mobile application, but its not recommended form a security point of view, and you will also need to re-implement all logic on both the web and mobile application.

Body:
You need to make your php based web application 'service-oriented', i.e. it acts as a web service endpoint and only processes requests and responds with XML/JSON/text data. This interface will be available for use to both your mobile application and your web application (use ajax to communicate with the service).

In this case your web-application and mobile-application act as presentation layer for the data received from the web-service. However, because of how crawlers parse web sites, your ajax based web-application will not be readable by them. If you need your web-application to be readable by the crawlers then you need to introduce another layer that interacts with the web-service and presents the information as general HTML based page.

So your web app will be like:

Client >> Presentation-Layer (js) >[HTTP]> Service-Layer (php) >> DB (MySQL)

Or,

Client >[HTTP]> Presentation-Layer (php) >[HTTP]> Service-Layer (php) >> DB (MySQL)

if you want it to be parsable by crawlers.

And your mobile app will be like:

Client >> Presentation-Layer (java/obj-C) >[HTTP]> Service-Layer >> DB (MySQL)

You can also connect remotely to your main database from both the web application as well as the mobile application, but its not recommended form a security point of view, and you will also need to re-implement all logic on both the web and mobile application.


问:
The balance between client and server functionality
I want to bring the discussion that started in our teams and get your opinion about it.

Assume we have an user account which could have different credentials for authentication and associated email to recover. An user has possibility to do signup with an email or use his social profile to complete signup process.

As an Rest API from the backend to client looks like:

Create account

Authorise

Update user data

Link social account

Register email

Verify email

In addition our BE is distributed and divided between several services/servers/clusters. So different calls are related to different end points. As well we have different client - mobile native applications, web application.

The usual registration flow looks for the client like this:

Ask user for email

Create account (Rest)

Authorise (Rest)

Ask user for his display name

Update data (Rest)

Register email (Rest)

And future possible calls:

Verify email

Link social account to user

With the Facebook signup:

Ask user to login to FB

Create account (Rest)

Authorise (Rest)

Link FB (Rest)

Register and verify FB user email (Rest)

Update user name based on FB data (Rest)

But all these steps are possible to do on backend. So we proposed to have another end point which will hide/combine different calls on BE and return whole process result to the clients:

Ask user for FB login

New user with FB (proposed Rest)

BE is doing register/link verified email/update user data/authorise

The pros for this approach:

No more duplication of functionality between clients

Speed up the networking and user experience

The cons for this approach:

Additional work for backend

Probably most complex scenarios in future updates

I would like to get your opinion or experience with this situation. Especially if you already experienced point "Probably most complex scenarios in future updates" from against reasons.

答:
Point 2 is reasonable argument against the use of the given approach. I worked on something similar where user can have data in different form depending on the entry point. Obviously, complexity of your code is going to increase as per the number of new flows you introduce but depending on benefits involved sometimes you have to add new user flows. If you do not have use cases with insanely high branching factor, you can easily manage complexity if you focus on few things.

Try to make things readable at each level. Whether you are exposing your API or writing code, keep everything meaningful both for your programmers and API users. If you take care of readability, smaller things like naming etc., things will become less complex.

Do not rely on data patterns in your storage expect a few key fields, you will have to be careful while defining what is you always going to have. For example, you have created your API assuming, you will always have this field filled by the user but then you introduce a new use case where that field is not mandatory. You might have hard time changing your code for that.

Follow standard coding principles that our elders have been teaching us like KISS, SOLID, design patterns etc. This one also includes my first point but that has been mentioned separately because that is the worst thing in a complex scenario.


问:
Permissions and MVC
I’m in the progress of developing a web application. This web application is mostly a CRUD interface, although some users are only allowed to perform some actions and see only some parts of views.

What would be a reasonable way to handle user permissions, given that some parts of views are not available to users? I was thinking of having a function hasPermission(permission) that returns true iff the current user has the given permission, although it would require conditionals around all parts of views that are only visible to some users. For example:

```<code>{% if has_permission('view_location') %}
    {{ product.location }}
{% endif %}
</code>```

I’m fearing this will become an ugly and unreadable mess, especially since these permissions can get kind of complicated.

How is this problem commonly solved in web applications?

I’m considering using Haskell with Happstack or Python with Django.

答:
I'm not sure how it is normally accomplished in other frameworks, but I created a small PHP framework that essentially had a similar method to the one you described to trigger permission logic.

I would imagine in Django you could create different view templates that include or not include the parts of the view that need permissions and return different views based on permissions, which could be controlled mostly in views.py.  I'm not really sure how else you could accomplish permission logic any more simply than a simple flag or returning different views.

Title: Permissions and MVC


问:
Is there a reason someone would choose GPLv2 instead of GPLv3?
Is there any reason anyone would use GPL v2 over GPL v3 when starting a new project, or is GPL v2 still around only because older projects can't or haven't updated their license yet?</p>

答:
If you use GPL v3 you give up your right to assert patents you have on the technology.

If you own patents and want to monetize these, don't distribute your patented code under GPL v3.


问:
Inherit one instance variable from the global scope
I'm using Curses to create a command line GUI with Ruby. Everything's going well, but I have hit a slight snag. I don't think Curses knowledge (esoteric to be fair) is required to answer this question, just Ruby concepts such as objects and inheritance.

I'm going to explain my problem now, but if I'm banging on, just look at the example below.

Basically, every Window instance needs to have .close called on it in order to close it. Some Window instances have other Windows associated with it. When closing a Window instance, I want to be able to close all of the other Window instances associated with it at the same time.

Because associated Windows are generated in a logical fashion, (I append the name with a number: instance_variable_set(self + integer, Window.new(10,10,10,10)) ), it's easy to target generated windows, because methods can anticipate what assosiated windows will be called, (I can recreate the instance variable name from scratch, and almost query it: instance_variable_get(self + integer).

I have a delete method that handles this. If the delete method is just a normal, global method (called like this: delete_window(@win543) then everything works perfectly. However, if the delete method is an instance method, which it needs to be in-order to use the self keyword, it doesn't work for a very clear reason; it can 'query' the correct instance variable perfectly well (instance_variable_get(self + integer)), however, because it's an instance method, the global instances aren't scoped to it!

Now, one way around this would obviously be to simply make a global method like this: delete_window(@win543). But I have attributes associated with my window instances, and it all works very elegantly.

This is very simplified, but it literally translates the problem exactly:

```<code>class Dog
        def speak
                woof
        end
end

def woof
        if @dog_generic == nil
                puts "@dog_generic isn't scoped when .woof is called from a class method!\n"
        else
                puts "@dog_generic is scoped when .woof is called from the global scope. See:\n" + @dog_generic
        end
end

@dog_generic = "Woof!"
lassie = Dog.new
lassie.speak #=> @dog_generic isn't scoped when .woof is called from an instance method!\n

woof #=> @dog_generic is scoped when .woof is called from the global scope. See:\nWoof!
</code>```

TL/DR: I need lassie.speak to return this string: "@dog_generic is scoped when .woof is called from the global scope. See:\nWoof!" @dog_generic must remain as an insance variable. The use of Globals or Constants is not acceptable.

Could woof inherit from the Global scope? Maybe some sort of keyword:

```<code>def woof < global # This 'code' is just to conceptualise what I want to do, don't take offence!
end
</code>```

Is there some way the .woof method could 'pull in' @dog_generic from the global scope? Will @dog_generic have to be passed in as a parameter?

答:
You should be able to get that from instance_variable_get(:@dog_generic) but there is an implied self in that call.  So, this means we would have to specify exactly what object you want to get that instance variable from.  And the fact that it is an instance variable implies you need to specify which instance of which object.  Therein lies the puzzle, right?

And so, somewhere, you could pass self from that point, where self is 'main' (which is of class Object).

```<code>class Dog
  def initialize(generic_dog)
    @from_outside = generic_dog # => main
  end
  def speak
    @from_outside.instance_variable_get(:@dog_generic) # => "Woof!"
  end
end

def woof
  if @dog_generic == nil
    "@dog_generic isn't scoped when .woof is called from a class method!\n"
  else
    "@dog_generic is scoped when .woof is called from the global scope. See:\n" + @dog_generic
  end
end

@dog_generic = "Woof!"
lassie = Dog.new(self)
puts lassie.speak
puts woof

# Output shown as >> and returns shown as =>
# >> Woof!
# >> @dog_generic is scoped when .woof is called from the global scope. See:
# >> Woof!
</code>```

So, no, @dog_generic doesn't necessarily need to be passed in as an argument, but you do need to pass something in somewhere.

I changed the if statement to not use puts as unconditionally putsing is not DRY, and we probably want to return the result of the_if statement_ rather than return nil from the method.  So we puts the method being called.

Body:
You should be able to get that from instance_variable_get(:@dog_generic) but there is an implied self in that call.  So, this means we would have to specify exactly what object you want to get that instance variable from.  And the fact that it is an instance variable implies you need to specify which instance of which object.  Therein lies the puzzle, right?

And so, somewhere, you could pass self from that point, where self is 'main' (which is of class Object).

class Dog
  def initialize(generic_dog)
    @from_outside = generic_dog # => main
  end
  def speak
    @from_outside.instance_variable_get(:@dog_generic) # => "Woof!"
  end
end

def woof
  if @dog_generic == nil
    "@dog_generic isn't scoped when .woof is called from a class method!\n"
  else
    "@dog_generic is scoped when .woof is called from the global scope. See:\n" + @dog_generic
  end
end

@dog_generic = "Woof!"
lassie = Dog.new(self)
puts lassie.speak
puts woof

# Output shown as >> and returns shown as =>
# >> Woof!
# >> @dog_generic is scoped when .woof is called from the global scope. See:
# >> Woof!

So, no, @dog_generic doesn't necessarily need to be passed in as an argument, but you do need to pass something in somewhere.

I changed the if statement to not use puts as unconditionally putsing is not DRY, and we probably want to return the result of the_if statement_ rather than return nil from the method.  So we puts the method being called.


答:
You could store the permissions in the user table in your database:

```<code>user
  allow_one_area
  allow_another_area
  perm_fiddle_this
  perm_toggle_that
  perm_modify_other_users
  perm_add_users
</code>```

Then just check the appropriate fields before letting a given user access one part of the system or perform a certain activity.

Title: Permissions and MVC

Body:
I’m in the progress of developing a web application. This web application is mostly a CRUD interface, although some users are only allowed to perform some actions and see only some parts of views.

What would be a reasonable way to handle user permissions, given that some parts of views are not available to users? I was thinking of having a function hasPermission(permission) that returns true iff the current user has the given permission, although it would require conditionals around all parts of views that are only visible to some users. For example:

```<code>{% if has_permission('view_location') %}
    {{ product.location }}
{% endif %}
</code>```

I’m fearing this will become an ugly and unreadable mess, especially since these permissions can get kind of complicated.

How is this problem commonly solved in web applications?

I’m considering using Haskell with Happstack or Python with Django.

Body:
You could store the permissions in the user table in your database:

user
  allow_one_area
  allow_another_area
  perm_fiddle_this
  perm_toggle_that
  perm_modify_other_users
  perm_add_users

Then just check the appropriate fields before letting a given user access one part of the system or perform a certain activity.


问:
UI design and confirmation paradigm
I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that "now some are getting rid of the OK button". The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.

Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.

However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

TL;DR: Remove OK/cancel confirmation, what happens?

EDIT:

Mac GUI for appearance settings.

答:
The thing is, that works very well with technically proficient, confident users.  However, I think you'd run into a world of hurt with non-proficient users who frequently, say, mis-click, or change a setting other than the one they intend, and suchlike - especially if the dialog that you just closed without a confirmation is hard to find for non-proficient users.

Less "are you sure?" dialogs would be great for me - but it would kill my mother.

ContentLicense: CC BY-SA 2.5

Title: UI design and confirmation paradigm


问:
How to structure my GUI agnostic project?
I have a project which loads from database a XML file which defines a form for some user. XML is transformed into a collection of objects whose classes derive from single parent. Something like

Control -> EditControl -> TextBox

Control -> ContainterControl -> Panel

Those classes are responsible for creation of GUI controls for three different enviroments: WinForms, DevExpress XtraReports and WebForms. All three frameworks share mostly the same control tree and have a common single parent (Windows.Forms.Control, XrControl and WebControl).

So, how to do it?

Solution a) Control class has abstract methods

```<code>Control CreateWinControl();
XrControl CreateXtraControl();
WebControl CreateWebControl();
</code>```

This could work but the project has to reference all three frameworks and the classes are going to be fat with methods which would support all three implementations.

Solution b) Each framework implementation is done in separate projects and have the exact class tree like the Core project. All three implementations are connected using a interface to the Core class.

This seems clean but I'm having a hard time wrapping my head around it. Does anyone have a simpler solution or a suggestion how should I approach this task?

答:
If you have a tree of objects (and I do mean tree of objects, not tree of classes) of various types that you want to process in different ways, then the common approach is to use the visitor pattern.

How would that look in your case? Your common project would contain an abstract class ControlTreeVisitor, which would look something like this (simplified by assuming there is no ContainterControl or EditControl):

```<code>public abstract class ControlTreeVisitor
{
    protected virtual void VisitControl(Control control)
    {
        // dispatch to the appropriate Visit* method
    }

    protected virtual void VisitPanel(Panel panel)
    {
        foreach (var childControl in panel.Children)
        {
            VisitControl(childControl);
        }
    }

    protected virtual void VisitTextBox(TextBox textBox)
    {
        // do nothing
    }
}
</code>```

Each GUI-specific project would then contain a concrete class that would inherit from this visitor class and would override all the Visit* methods to create the appropriate control tree for the given GUI library.

There are some possible alternatives in the design of the visitor base class. For example, one variation would be to make it generic, where the type parameter would represent the  base class in the specific GUI library (e.g. class WebControlVisitor : ControlTreeVisitor<WebControl>). All Visit* methods would then return this type. This would make creating a tree of WebControls simpler.

Body:
If you have a tree of objects (and I do mean tree of objects, not tree of classes) of various types that you want to process in different ways, then the common approach is to use the visitor pattern.

How would that look in your case? Your common project would contain an abstract class ControlTreeVisitor, which would look something like this (simplified by assuming there is no ContainterControl or EditControl):

public abstract class ControlTreeVisitor
{
    protected virtual void VisitControl(Control control)
    {
        // dispatch to the appropriate Visit* method
    }

    protected virtual void VisitPanel(Panel panel)
    {
        foreach (var childControl in panel.Children)
        {
            VisitControl(childControl);
        }
    }

    protected virtual void VisitTextBox(TextBox textBox)
    {
        // do nothing
    }
}

Each GUI-specific project would then contain a concrete class that would inherit from this visitor class and would override all the Visit* methods to create the appropriate control tree for the given GUI library.

There are some possible alternatives in the design of the visitor base class. For example, one variation would be to make it generic, where the type parameter would represent the  base class in the specific GUI library (e.g. class WebControlVisitor : ControlTreeVisitor<WebControl>). All Visit* methods would then return this type. This would make creating a tree of WebControls simpler.


问:
How to decide between using an existing eCommerce solution and building your own?
There are a number of both open and close source off the shelf solutions.  For example Magento has an impressive list of sites that use them for eCommerce.  There are also stories such as this (only link to last section) where an eCommerce site is developed from scratch with great success.

I'm wondering if there's an objective way to approach the build vs customize decision?

答:
There is a very good post on it here http://www.getelastic.com/webinar-recap-the-new-ecommerce-dilemma-buy-build-or-leverage/ Despite it's been a while since this post was written it's still relevant From my point of view, the idea that you can find an "out-of the-box" solution for your company is rather an illusion. Every merchant in the market is competing with the e-shopping experience he provides to his customers. In order to succeed you need your visitor's experience to be unique. That's why many of the major eCommerce merchants (more than 50%) chose in house development.

Definitely, doing in house you want to reduce the amount of efforts and time to market. That's where you can use a framework as a starting point.


答:
Solution (b) is the way to go. Define interfaces for the various controls:

```<code>public interface EditControl
{
  //...
}

public interface ContainerControl
{
  //...
}
</code>```

and an interface for a factory:

```<code>public interface ControlFactory
{
  EditControl CreateEditControl(...);
  ContainerControl CreateContainerControl(...);
  //...
}
</code>```

Each of the packages will then implement this set of interfaces; in particular, each package knows how to implement the ControlFactory interface by creating its own flavour of the controls.

Title: How to structure my GUI agnostic project?

Body:
I have a project which loads from database a XML file which defines a form for some user. XML is transformed into a collection of objects whose classes derive from single parent. Something like

Control -> EditControl -> TextBox

Control -> ContainterControl -> Panel

Those classes are responsible for creation of GUI controls for three different enviroments: WinForms, DevExpress XtraReports and WebForms. All three frameworks share mostly the same control tree and have a common single parent (Windows.Forms.Control, XrControl and WebControl).

So, how to do it?

Solution a) Control class has abstract methods

```<code>Control CreateWinControl();
XrControl CreateXtraControl();
WebControl CreateWebControl();
</code>```

This could work but the project has to reference all three frameworks and the classes are going to be fat with methods which would support all three implementations.

Solution b) Each framework implementation is done in separate projects and have the exact class tree like the Core project. All three implementations are connected using a interface to the Core class.

This seems clean but I'm having a hard time wrapping my head around it. Does anyone have a simpler solution or a suggestion how should I approach this task?

Body:
Solution (b) is the way to go. Define interfaces for the various controls:

public interface EditControl
{
  //...
}

public interface ContainerControl
{
  //...
}

and an interface for a factory:

public interface ControlFactory
{
  EditControl CreateEditControl(...);
  ContainerControl CreateContainerControl(...);
  //...
}

Each of the packages will then implement this set of interfaces; in particular, each package knows how to implement the ControlFactory interface by creating its own flavour of the controls.


答:
I think that there is a simple answer to this, in my view its not so much that its bad as that the choices - compromises - that they made in order to produce a productive framework are not ones that you agree with.

That said the ease with which you can do (and I have done) really stupid things and the amount of bloat that you can trivially add to a page are good arguments for why its flawed.

The flip side of this is that you can do a lot of clever things with not a lot of effort - and if you're targeting a focused site for internal use for a business as opposed to a wider public facing website then the productivity gains can be a huge win.

With the ongoing development of the webforms framework and with developers that have a clue you don't now have to produce poor bloated pages any more either (though lots of people still will).


问:
Dependency injection with Finite State Machines and the Interface Segregation Principle
I am trying to figure out what is the best way to setup a FSM and also keep my interfaces clean and use an IOC container to use DI.

Let's just visit the Head First design pattern textbook example of the gumball machine.

```<code>interface IState
{
    InsertQuarter();
    EjectQuarter();
    TurnCrank();
    Dispense();
}
</code>```

Is the best practice to just thrown an exception for an invalid state?  Why add the state if it's not even applicable?  I guess that is the portion where I am confused.  I could see this simple example getting more complex.

My other related question is, how do I perform DI to these states?  Should a state machine and states should be registered in my IOC container?  Let's suppose I have an Order Service and an Inventory Service that have a dependency on a StageOrderState.  What might this object model look like?  I'm having a hard time digesting how to actually inject the dependencies in to these states.  My guess is that I could register the states and pass the container around to the states.

答:
For the first question: the states are not invalid in general. The actions only make sense in certain states. For example, calling EjectQuarter() will not make sense if you haven't previously called InsertQuarter(). If that happens, how do you want to proceed? Deep inside business logic, throwing an exception makes sense (there is no reasonable way to proceed); catch that exception and display an error message up in the UI layer.

For your second question, I don't think DI is meant for states (values); it's meant to inject services that other services depend on. You can inject an entire FSM into an Inventory Service; if you have methods that should behave differently depending on the state a FSM is in, either pass in the state to those methods, or pass in the FSM to the Inventory Service and let it ask the FSM about its current state. (I recommend the first option - I see no reason for an Inventory Service to know what an FSM is.)


问:
unit level testing, agile, and refactoring
I'm working on a very agile development system, a small number of people with my doing the vast majority of progaming myself.

I've gotten to the testing phase and find myself writing mostly functional level testing, which I should in theory be leavning for our tester (in practice I don't entirely...trust our tester to detect and identify defects enough to leave him the sole writter of functional tests).  In theory what I should be writing is Unit level tests.

However, I'm not sure it's worth the expense.  Unit testing takes some time to do, more then functional testing since I have to set up mocks and plugs into smaller units that weren't design to run in issolation.  More importantly, I find I refactor and redesign heavily-part of this is due to my inherriting code that needed heavy redesign and is still being cleaned up, but even once I've finished removing parts that need work I'm sure in the act of expanding the code I'll still do a decent amount of refactoring and redesign.  It feels as if I will break my unit tests, forcing wasted time to refactor them as well, often due to unit test, by definition, having to be coupled so closely to the code structure.

So.is it worth all the wasted time when functional tests, that will never break when I refactor/redesign, should find most defects?  Do unit tests really provide that much extra defect detetection over through functional?  and how does one create good unit tests that work with very quick and agile code that is modified rapidly?

ps, I would be fine/happy with links to anything one considers an excellent resource for how to 'do' unit testing in a highly changing enviroment.

edit: to clarify I am doing a bit of very unoffical TDD, I just seem to be writing tests on what would be considered a functional level rather then unit level.  I think part of this is becaus I own nearly all of the project I don't feel I need to limit the scope as much; and part of it is that it's daunting to think of trying to go back and retroactively add the unit tests needed to cover enough code that I can feel comfortable testing only a unit without the full functionality and trust that unit still works with the rest of the units.

答:
Ah... you're most definitely not doing TDD. TDD is Test-Driven Design; in particular, it's writing the specifications (aka tests) first. What you're doing is writing tests (which is fine, and normally quite useful - after all, we need to test the code, it's just that most of us are fine with doing that manually).

As for unit tests vs functional tests; in my view, the fact that you "refactor and redesign heavily" is the main benefit of unit tests. I like that the resulting code is designed better than it was when I started. Whether that effort is justified is, unfortunately, rather subjective.

I wouldn't focus on "trying to go back and retroactively add the unit tests needed to cover enough code"; try adding tests around pieces of functionality that you feel are complicated enough to warrant it. I have a particular example where I had to add tests because a view in the project I'm working on had a lot of logic in it for displaying the correct time depending on the market and time-zone. It wasn't TDD - the production code was already there - but I wanted to make sure that it works correctly in various cases I could think of. I do not believe that those tests will need to be changed for anything short of a changing business requirement.

I will end by pointing to the obligatory "Working Effectively with Legacy Code" reference.


问:
Implementing set of processes in a stored procedure or through the code?
I want to know what's the suitable method to implement the following case (best practice).

If i make a set of processes like this:

select data from set of DB tables.

loop on the selected result.

Make some checks on each iteration.

Insert the result in another table.

Implementing the previous steps in a stored procedure or in a transaction through my code (asp.net)? Concerning the performance, security and reliability issues.

答:
Both will Work, which to choose depends on other factors not specified in your question.

Those factors include (but are not limited to)

Performance requirements, and other related factors (How much data
needs to be shuffled back and forth between the server and DB)

Requirements to support multiple Backbends and or change backends

Talent available to maintain the code base


问:
Throwing exception from a property when my object state is invalid
I am aware that for the general case, the answer to "should I throw an exception from a property" is "generally don't, but in some special circumstances it is OK to do so". There is a Microsoft guideline which gives this general answer, and also a question on this site.

Now I am faced with a situation which I think may be one of those "special ones" where it is OK. My question: is this really one of those exceptional situations where throwing the exception is superior to the alternatives? Or is it better to use a getter/setter just like in the general case?

My application uses Linq2SQL, and there is the case where my object can be in invalid state because somebody or something wrote nonsense into the database. Consider this toy example:

```<code>[Table(Name="Rectangle")]
public class Rectangle {

[Column(Name="ID", IsPrimaryKey = true, IsDbGenerated = true)]
public int ID {get; set;}

[Column(Name="firstSide")]
public double firstSide {get; set;}

[Column(Name="secondSide")]
public double secondSide {get; set;}

public double sideRatio
{
    get
    {
            return firstSide/secondSide;
    }
}
}
</code>```

Here, I could write code which ensures that my application never writes a Rectangle with a zero-length side into the database. But no matter how bulletproof I make my own code, somebody could open the database with a different application and create an invalid Rectangle, especially one with a 0 for secondSide. (For this example, please forget that it is possible to design the database in a way such that writing a side length of zero into the rectangle table is impossible; my domain model is very complex and there are constraints on model state which cannot be expressed in a relational database).

So, the solution I am gravitating to is to change the getter to:

```<code>get
{
     if(firstSide > 0 && secondSide > 0) return firstSide/secondSide;
     else throw new System.InvalidOperationException("All rectangle sides should have a positive length");
}
</code>```

The reasoning behind not throwing exceptions from properties is that programmers should be able to use them without having to make precautions about catching and handling them them. But in this case, I think that it is OK to continue to use this property without such precautions:

if the exception is thrown because my application wrote a non-zero rectangle side into the database, then this is a serious bug. It cannot and shouldn't be handled in the application, but there should be code which prevents it. It is good that the exception is visibly thrown, because that way the bug is caught.

if the exception is thrown because a different application changed the data in the database, then handling it is outside of the scope of my application. So I can't do anything about it if I catch it.

Is this a good enough reasoning to get over the "avoid" part of the guideline and throw the exception? Or should I turn it into a method after all? Note that in the real code, the properties which can have an invalid state feel less like the result of a calculation, so they are "natural" properties, not methods.

答:
You can choose to never let the application build an invalid instance of your object.

```<code>private double _firstSide;

[Column(Name="firstSide")]
public double FirstSide {
    get { return this._firstSide; }
    set
    {
        if(value <= 0) throw new System.InvalidOperationException("All rectangle sides should have a positive length");
        this._firstSide = value;
    }
}

private double _secondSide;

[Column(Name="secondSide")]
public double SecondSide
{
    get { return this._secondSide; }
    set
    {
        if(value <= 0) throw new System.InvalidOperationException("All rectangle sides should have a positive length");
        this._secondSide = value;
    }
}

public double SideRatio
{
    get
    {
        return this.FirstSide / this.SecondSide; // safe
    }
}
</code>```

Handle the errors when you are building your instance / setting your properties. When it's time to do some algorithms, you can safely access SideRatio without the overhead to handle weird objects.

This way, you have a clear distinction between data access layer which will validate objects, and the use of this objects, which are guaranteed to be safe.

Body:
You can choose to never let the application build an invalid instance of your object.

private double _firstSide;

[Column(Name="firstSide")]
public double FirstSide {
    get { return this._firstSide; }
    set
    {
        if(value <= 0) throw new System.InvalidOperationException("All rectangle sides should have a positive length");
        this._firstSide = value;
    }
}

private double _secondSide;

[Column(Name="secondSide")]
public double SecondSide
{
    get { return this._secondSide; }
    set
    {
        if(value <= 0) throw new System.InvalidOperationException("All rectangle sides should have a positive length");
        this._secondSide = value;
    }
}

public double SideRatio
{
    get
    {
        return this.FirstSide / this.SecondSide; // safe
    }
}

Handle the errors when you are building your instance / setting your properties. When it's time to do some algorithms, you can safely access SideRatio without the overhead to handle weird objects.

This way, you have a clear distinction between data access layer which will validate objects, and the use of this objects, which are guaranteed to be safe.


答:
Any time you have to move data from the server to a client and back, you are going to hit a performance wall. It may be acceptable, it may not be. You will have to do the testing to figure that out.

I personally stick with stored procedures for my database access, because I like keeping the logic surrounding data with the data, rather than in the application layer, which consumes data.

The most concerning thing to me about your question is that you want to loop over rows--typically, that means you aren't using SQL correctly. SQL works best on sets, and database engines are optimized for set-based work. Unless you absolutely cannot work on the data in a set-based approach, I would advise you to avoid loops.

Title: Implementing set of processes in a stored procedure or through the code?

Body:
I want to know what's the suitable method to implement the following case (best practice).

If i make a set of processes like this:

select data from set of DB tables.

loop on the selected result.

Make some checks on each iteration.

Insert the result in another table.

Implementing the previous steps in a stored procedure or in a transaction through my code (asp.net)? Concerning the performance, security and reliability issues.


问:
What will be the better way for data retrieval on application that needs to handle limited amount of data.?
This is not really a coding question since, I am not adding any code in here. Since, adding my code snippets itself would make this question really long. Instead, I am pretty interested in knowing a better ways for data retrieval on application that needs to handle limited amount of data which isn't updated regularly. Let's take this example:

I am writing an application which gets a schedule as an XML from server. I have written a logic in order to parse XML version and update database only if the version is newer than the local version. Although the update is checked automatically/manually on daily basis based on user preference, the actual version update happens only once per few months or so. Since, this  is done by some other authority which doesn't provide API but, rather inform publicly on their changes.

The actual XML contains a "(n number of groups)(days in a week) (n number of schedule)" . The group is usually 6 and the number of schedule is usually 2. So basically there would usually be only around 100 strings.

Now although I have used SQLite at the moment. I want to know how to make update on database. Should I show progress dialog that the application is updating and exit the app when it's done? Since, my updates are infrequent i don't think this will really harm user experience but, is there any better ways to do it? Because I don't want update to be made when user is searching which is done using database. This will cause an database already open exception. Atleast I have faced this problem before.

Is it better to rather parse XML every time when user wants to view certain things or to use SQLite? Since, I make lots of use of adapter in my app to create lists, will that degrade the performance?

It would really be a great help if anyone can give me better overview about it. Or may be counter argument against each.

Many thanks!

答:
1- Since the updates are infrequent, you have a good chance to do them in a background service, so it won't interrupt the user experience.

2- It is a bad idea to parse the XML every time since it does not change that often, using SQLite will be much faster.

OwnerDisplayName: Milanix

OwnerDisplayName: iTech


问:
Which one is better offline method for large scale application
We've a big data management website used by several property. Some of our customers have downtime (they can't access net for an hour or two). We want our site to support offline data viewing and inventory management (typical data search and add/remove) and when the user goes online we can sync the changes back to our central database. Customers use several platforms like Windows, iOS, etc.

We've been looking into several different options, here are the major choices -

Develop offline web app supported in HTML5. Develop a 'fallback' mechanism and interact with data from the app cache as explained in here (http://www.htmlgoodies.com/html5/tutorials/introduction-to-offline-web- applications-using-)

Develop a desktop based cross platform solution. I remember the old MONO which has been popular. Here's a post (What do you suggest for cross platform apps, including web cross-platform-apps-including-web) and another one (Technology choice for cross platform development (desktop and phone)? platform-development-desktop-and-phone?rq=1)

I realize the the desktop solution might be hard to maintain and result in some compatibility issues and demand test environments.

Can HTML5 handle moderate to high level complexity and data flow? Or would it be better to rely on a desktop based app for better scalability & performance?

答:
If you can ignore Management and Customer expectations, along with your team's existing skill set and existing code, I'd go with the desktop solution.  In fact, ditch the browser system completely and do it all from the desktop.

Long term, a desktop application, written in a language like C# or Java, has got to be vastly easier to maintain than a large-scale web system written in HTML and Javascript.  Unless people need to get at your site using ordinary machines (like the one they just sat down at in the public library) with ordinary browsers, I'd make the system an app.

(That is, if you can ignore ...)


答:
Define "better". That word means different things to different people when asked at different times.

I would suggest HTML5 (especially if your users can't always install apps) if you or your team are proficient in Javascript and HTML/CSS. I feel JS is a very effective and easy to manage language if you properly understand how to use it.

If you or your team are more proficient with Mono et al, then I would do that direction. Though, I would assume to implement offline mode and syncing in Mono would be a bit more complex that in JS with HTML5's APIs.

Offline mode approaches are all quite similar in that you must track data locally and be able to successfully sync it up from the local schema to a remote schema while effectively (ideally automatically) resolving diff/merge issues.

Title: Which one is better offline method for large scale application

Body:
We've a big data management website used by several property. Some of our customers have downtime (they can't access net for an hour or two). We want our site to support offline data viewing and inventory management (typical data search and add/remove) and when the user goes online we can sync the changes back to our central database. Customers use several platforms like Windows, iOS, etc.

We've been looking into several different options, here are the major choices -

Develop offline web app supported in HTML5. Develop a 'fallback' mechanism and interact with data from the app cache as explained in here (http://www.htmlgoodies.com/html5/tutorials/introduction-to-offline-web- applications-using-)

Develop a desktop based cross platform solution. I remember the old MONO which has been popular. Here's a post (What do you suggest for cross platform apps, including web cross-platform-apps-including-web) and another one (Technology choice for cross platform development (desktop and phone)? platform-development-desktop-and-phone?rq=1)

I realize the the desktop solution might be hard to maintain and result in some compatibility issues and demand test environments.

Can HTML5 handle moderate to high level complexity and data flow? Or would it be better to rely on a desktop based app for better scalability & performance?


问:
Requring static class setter to be called before constructor, bad design?
I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList.

Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called.

I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

答:
Another possible solution would be to use the Singleton design pattern.

A real world example would be if a worker has a task to do and that task requires the use of a shared list why should the manager have to tell the worker what list to use when his/her task already knows which list is needed?

Make the myList class a singleton then in the constructor of the Foo class have it get a pointer to the one instance of the myList object.

```<code>Class myList
{
  static myList * get_instance()
  {
    static myList m_instance;
    return &m_instance;
  }
};

Class Foo
{
  public Foo()
  {
    myList * m_list = MyList::get_instance();
  }
};
</code>```

This solution is the simplest for the requirements stated because it does not required the code creating the object to even care about the shared list but simply creates the Foo object.

Body:
Another possible solution would be to use the Singleton design pattern.

A real world example would be if a worker has a task to do and that task requires the use of a shared list why should the manager have to tell the worker what list to use when his/her task already knows which list is needed?

Make the myList class a singleton then in the constructor of the Foo class have it get a pointer to the one instance of the myList object.

Class myList
{
  static myList * get_instance()
  {
    static myList m_instance;
    return &m_instance;
  }
};

Class Foo
{
  public Foo()
  {
    myList * m_list = MyList::get_instance();
  }
};

This solution is the simplest for the requirements stated because it does not required the code creating the object to even care about the shared list but simply creates the Foo object.


问:
Tips for Tail Call Recursion in Python
Ok, Python doesn't have tail call optimization.

But for those who think better recursively than "looply", whats the best practices to write code??

1000 stack calls are enough for many cases, but what are the tips to conceal recursion with efficiency in Python?

答:
Well if you're writing tail recursive algorithms, you're probably doing something like this

```<code> def my_algo(whatever)
   if some_condition:
       return foo
   ...
   return my_algo(bar)
</code>```

Since the call to my_algo is necessarily the last thing to return, it's pretty easy to translate this to

```<code> def my_algo(whatever)
   while some_condition:
       ...
       whatever = bar
   return whatever
</code>```

This is actually basically what happens with tail call optimization in most compilers anyways.

Title: Tips for Tail Call Recursion in Python

Body:
Well if you're writing tail recursive algorithms, you're probably doing something like this

 def my_algo(whatever)
   if some_condition:
       return foo
   ...
   return my_algo(bar)

Since the call to my_algo is necessarily the last thing to return, it's pretty easy to translate this to

 def my_algo(whatever)
   while some_condition:
       ...
       whatever = bar
   return whatever

This is actually basically what happens with tail call optimization in most compilers anyways.