问:
Is browser fingerprinting a viable technique for identifying anonymous users?
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/

答:
Is browser fingerprinting a sufficient method for uniquely identifying
  anonymous users?

No, at best it can uniquely identity a Computer. There is no way it can differentiate between 2 new (and like) computers on the same network (Same IP) with out a cookie\session.

What if you incorporate biometric data like mouse gestures or typing
  patterns?

This doesn't seem realistic. This would have to be coded almost entirely in JavaScript as "bio-metric data" is all client side. The user can just shut it off. Also what will your "bio-metric data" look like for a Perl Script?

That being said, using these kind of tactics to fight fraud is a good idea, It doesn't have to be a 100%.. any decrease in fraud is good, even if its just a 5% improvement.

The fight against fraud is an incremental one, there is no single bullet solution to fight fraud, don't even bother looking for one.

EDIT:
To reply to the Comments Below (and because it is very relevant), the fact that fingerprinting treats different profiles is, in My beliefs, a net NEGATIVE*. This is something that a malicious user will use to fool the fingerprinting mechanism, the fact that the user has control over all the variables used in fingerprinting is a serous flaw in and of itself.

*Which is why I say at best it can Identify a single computer, because that is BETTER then identifying a single Account on a Computer. If you can do both, that is great.


问:
Increase Performance of VS 2010 by using a SSD
After searching on the internet for performance improvements when using Visual Studio 2010 with a solid state hard drive, I heard a lot of different opinions.

A lot of people said that there isn't really a benefit when using a SSD, but in contrast others said the exact opposite. I am a bit confused with the contrasting opinions and I cannot really make a decision whether buying a SSD would make a difference.

What are your experiences with this issue and which SSD did you use?

答:
Visual Studio is sensitive to disk speed, but if you use TFS you're far more at the mercy of the speed of the TFS server and the network (since opening files and the initial modification requires a fetch and checkout).

If you use a DVCS, then target SSD -> CPU frequency.  Visual Studio is somewhat sensitive to CPU speed, and doesn't seem to be highly threaded.  Prefer fewer faster cores over more slower cores.  It doesn't seem to use much more than 1.5GB of RAM without running into OOM exceptions, so don't bother with shoving your machine full of more than 4GB of RAM.  If you are lucky enough to have over 4GB of RAM, use the extra as a RAM drive to store your source code in (draconian backup measures necessary).  Nothing can yet touch the speed of a RAM drive.  Here's a benchmark from my workstation:

ContentLicense: CC BY-SA 3.0


问:
What's the point of initializing a variable with the same value twice?
I was reading Ben Cherry's "JavaScript Module Pattern: In-Depth", and he had some example code that I didn't quite understand. Under the Cross-File Private State heading, there is some example code that has the following:

```<code>var _private = my._private = my._private || {}
</code>```

This doesn't seem to be different from writing something like this:

```<code>var _private = my._private || {}
</code>```

What's happening here and how are these two declarations different?

答:
```<code>var _private = my._private = my._private || {}
</code>```

This line means use my._private if it exists, otherwise create a new object and set it to my._private.

More than one assignment expression can be used in a statement.  The assignment operator uses (consumes) whatever is to the right of it and produces that value as its output to the left of the variable being assigned. So, in this case, with parentheses for clarity, the above is equivalent to var _private = (my._private = (my._private || {}))

This case is a type of lazy initialization.  A less terse version would be:

```<code>if (!my._private) {
    my._private = {};
}
var _private = my._private;
</code>```

In this case, it seems that the lazy initialization is more used for anywhere initialization than laziness.  In other words, all functions can include this line to safely create or use my._private without blowing away the existing var.

Body:
var _private = my._private = my._private || {}

This line means use my._private if it exists, otherwise create a new object and set it to my._private.

More than one assignment expression can be used in a statement.  The assignment operator uses (consumes) whatever is to the right of it and produces that value as its output to the left of the variable being assigned. So, in this case, with parentheses for clarity, the above is equivalent to var _private = (my._private = (my._private || {}))

This case is a type of lazy initialization.  A less terse version would be:

if (!my._private) {
    my._private = {};
}
var _private = my._private;

In this case, it seems that the lazy initialization is more used for anywhere initialization than laziness.  In other words, all functions can include this line to safely create or use my._private without blowing away the existing var.


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

(This is yet another example of a social issue being mistaken for a technical/design issue.)

There are two possibilities here:

Your client is expecting to be able to take the code you have written and adabpt or maintain it himself after you are done writing it. If so, you should know a lot more about the "house style" -- functional vs OO is only the tip of the iceberg. You will either need to limit yourself to a style of programming that your client understands, or you will need to educate your client in the styles you prefer. (Once, I was asked to build a web app with CGI, without using templating or libraries because the client might want to make changes.)

Your client is trying to control the development because of some agenda. This is a bag full of crazy that you want nothing to do with. If you are truly providing a "turnkey" piece of software, the client shouldn't care if it's made of hamsters running on wheels, as long as it does the job reliably. Allowing yourself to be micromanaged this way is just asking for pain.

It's up to you to decide which situation you're in, and act accordingly.


答:
I upgraded my computer a few months ago, and decided to test c++ build times before and after to see what sort of speed improvement I got. I tested three configurations, all building a C++ project in Visual Studio 2005 with Windows 7:

Core 2 duo ~2.6ghz, 4gb RAM, building a project from an SSD

Same system, building the same project from a 7.2k rpm hard disk

Core i5 2500k 3.3ghz, 8gb RAM, building the same project from an SSD

I did each build twice, one right after a warm boot, and again just after the first build (once everything had been swapped in to the disk cache). Here are the results I got:

First build – 96 seconds. Second build – 92 seconds.

First build – 96 seconds. Second build – 92 seconds.

First build – 54 seconds. Second build – 51 seconds.

In cases 1 and 2 you’ll note that I got exactly the same build times, regardless of whether I was building from my SSD, or the 7.2k RPM drive. So disk speed appears to not be a factor in compiling, at least for hard disks of a decent speed. The change that made the huge difference was going from a core 2 duo to a i5 3.3ghz CPU – so it appears that compilation is CPU bound, and not memory- or disk-bound.

I had been assuming that going from hard disk to SSD would increase speed a bit, but apparently that’s not the case – presumably everything just gets swapped in and after that goes at the speed of memory.

Title: Increase Performance of VS 2010 by using a SSD

Body:
After searching on the internet for performance improvements when using Visual Studio 2010 with a solid state hard drive, I heard a lot of different opinions.

A lot of people said that there isn't really a benefit when using a SSD, but in contrast others said the exact opposite. I am a bit confused with the contrasting opinions and I cannot really make a decision whether buying a SSD would make a difference.

What are your experiences with this issue and which SSD did you use?


问:
When should I use static variables with primitive types?
Recently I came across the question NSString: Why use static over literal? and in the comments arrived a new question.

In Objective-C there some "special" types that are just maps to C primitives. Like the NSInteger.

```<code>#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
</code>```

I know how to use the static keywords for objects but I don't understand the implications on C primitive types.

When should I use a static NSInteger x instead of NSInteger x? What happens with the memory in both cases?

答:
The static key word can have three meanings as it related to primitives

Declared inside a function. You could think of this as essentially creating a cache that only has scope in the function. The variable is only initialized once the first time the that function is called. The variable retains the same state it had from the previous call on all subsequent calls to the function. None static variables are put on the stack and have lifetime equivalent to duration of the function. The memory for static variables is someplace else and it always exists similarly to a global variable. In practice, I hardly see this used and personally, I don't think that I have ever used this outside of debugging.

Declared in global scope. Using a static variable in global scope simply limits the scope of the variable to the file it was declared in. It is a global variable, but it is only accessible from the scope/file that it was declared in. I use this all the time. It is certainly good practice from a data encapsulation standpoint, but it also helps limit possible namespace collisions. There is no difference in memory usage.

Declared in Class. This is similar to the first example. For each static variable in a class there is exactly one "copy" regardless of how many Class objects have been instantiated. It is sort of like a global variable that all instantiated objects of that type share.


答:
First, I don't think it's realistic to expect users to have JavaScript disabled on the modern web. So let's take a look at what Panopticlick can gather through JavaScript alone, along with the uniqueness score of my particular browser:

User Agent (1 in 4,184)

HTTP_ACCEPT Headers (1 in 14)

Browser Plugin Details (1 in 1.8 million)

Time Zone (1 in 24)

Screen Size and Color Depth (1 in 1,700)

System Fonts (1 in 11)

Cookies Enabled? (1 in 1.3)

Limited SuperCookie test (1 in 2)

The standouts for uniqueness are clearly User Agent and Browser Plugins. Remember that these items are used together to form a browser fingerprint, so they are more than as strong as the individual scores. The cumulative uniqueness here is: 4,184 x 14 x 1.8 million x 24 x 1,700 x 11 x 1.3 x 2 aka a REALLY BIG NUMBER. That's ... pretty unique.

I have Flash disabled at the moment, with "click to activate". Enabling Flash adds:

System Fonts (1 in 374k)

Flash provides the second most unique detectable element, but given the enormous number even the default JavaScript detection in Panopticlick produces, I'm not sure Flash is necessary for this sort of browser fingerprinting to work. Just JavaScript being enabled is enough.

Browser fingerprinting is merely a part of the story, though. Consider the sum of what all we can detect from anonymous users, because it can all work together to fingerprint anonymous users. How difficult is it to gather and use the detected data?

Browser detail sniffing, as shown above (easy)

IP Address, which has a known level of reliability with pros and cons (easy)

User behavior patterns such as usage (time of day), typing, mouse or finger movements, word use (hard, some server side, some client side)

One thing I worry about with browser sniffing alone is how trivially easy it is for users to switch browsers. There are at least four great and free browser alternatives on most platforms: Chrome, Opera, Firefox, Safari. So to break the browser sniffing, or at least interrupt it, you could switch browsers frequently.

It's worth mentioning so-called SuperCookies here since they can actually work, in some cases, even if you switch browsers and even if JavaScript, HTML 5 Local Storage, and Flash are disabled.

A privacy researcher has revealed the evil genius behind a for-profit web analytics service capable of following users across more than 500 sites, even when all cookie storage was disabled and sites were viewed using a browser's privacy mode.

(If you're curious, the TL;DR version is that they do this by exploiting obscure principles of the ETag header.)

Anyway, getting back to browser sniffing -- there are two somewhat inconvenient things users can do to defeat this:

Constantly switch browsers.

Always browse with JavaScript and Flash disabled.

However, if the user doesn't know that their browser settings are being sniffed and used as part of the method to fingerprint them, I highly doubt they would necessarily go to the trouble of doing these two things. It's work.

Based on the above data, I believe browser sniffing can help identify the typical anonymous internet user -- but it is only effective in combination with the other things we typically detect from anonymous internet users like IP Address.

Title: Is browser fingerprinting a viable technique for identifying anonymous users?

Body:
Is browser fingerprinting a sufficient method for uniquely identifying anonymous users? What if you incorporate biometric data like mouse gestures or typing patterns?

The other day I ran into the Panopticlick experiment EFF is running on browser fingerprints.

Of course I immediately thought of the privacy repercussions and how it could be used for evil. But on the other hand, this could be used for great good and, at the very least, it's a tempting problem to work on.

While researching the topic I found a few companies using browser fingerprinting to attack fraud. And after sending out a few emails I can confirm at least one major dating site is using browser fingerprinting as but one mechanism to detect fake accounts. (Note: They have found it's not unique enough to act as an identity when scaling up to millions of users. But, my programmer brain doesn't want to believe them).

Here is one company using browser fingerprints for fraud detection and prevention:

http://www.bluecava.com/

Here is a pretty comprehensive list of stuff you can use as unique identifiers in a browser:

http://browserspy.dk/


答:
Seconding the above responses that maybe OO isn't the best solution in which case the client may have a point.

Take a look at the AI Challenge which models some of the behaviour detailed in the question here http://aichallenge.org and then take a look at the variety of starter packages - http://aichallenge.org/starter_packages.php/ most are languages I wouldn't place within the OO paradigm.

Title: What would you do if your client required you not to use object-oriented programming?

Body:
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
C is portable assembly with better syntax, yielding the programmer full control of everything.

C++ on the other hand, does a lot of funky magic (virtual functions, overloading, automatic conversion, etc etc) which may not be desirable when you want to make sure you:

don't use more memory than you want to

don't access memory pages willy nilly (the vtable can be anywhere)

don't invoke to much code accidentally

And want something really simple to work with, since you're focused on performance.

It just has no surprises, and that's very valuable.

If you want to (and I recommend it), read the JSF coding guidelines on what you need to think about when writing C++ for military avionics control. It's a lot of traps in there that you need to be aware of, and it may catch you out. Bjarne was part of that document, so he knows what it's about.

Also, C compiles like a scalded troll struck by lightning. C++, OTOH, was probably sponsored by the same people who invested in SSD companies . :)

(Personally, I'd prefer C++ though, but I don't like it...... either. ;-P)

Title: When to use C over C++, and C++ over C?


答:
Even if there are a huge number of combinations, they are not all distributed evenly.

Think how many people on, say, a macbook, will just use the stock configuration. Or those who never install any plugin: I suspect those are the majority of users.

And at the extreme end, you have the fastest growing segment of devices: mobile phone and tablet users, especially iPhones and iPads, where you are reduced to only two variables: make, and version number.

So it might be a good heuristic when combined with other factors (such as ip address or location when available), but not much more than that.


问:
How should data be passed between client-side Javascript and C# code behind an ASP.NET app?
I'm looking for the most efficient / standard way of passing data between client-side JavaScript code and C# code behind an ASP.NET application. I've been using the following methods to achieve this but they all feel a bit of a fudge.

To pass data from JavaScript to the C# code is by setting hidden ASP variables and triggering a postback:

```<code><asp:HiddenField ID="RandomList" runat="server" />

function SetDataField(data) {
      document.getElementById('<%=RandomList.ClientID%>').value = data;
}
</code>```

Then in the C# code I collect the list:

```<code>protected void GetData(object sender, EventArgs e)
{
      var _list = RandomList.value;
}
</code>```

Going back the other way I often use either ScriptManager to register a function and pass it data during Page_Load:

```<code>ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true);
</code>```

or I add attributes to controls before a post back or during the initialization or pre-rendering stages:

```<code>Btn.Attributes.Add("onclick", "DisplayMessage("Hello");");
</code>```

These methods have served me well and do the job, but they just don't feel complete. Is there a more standard way of passing data between client side JavaScript and C# back-end code?

I've seen some posts like this one that describe HtmlElement class; is this something I should look into?

答:
I'd recommend having a look at jQuery. JQuery can be used to make AJAX calls back to the server, which can data back in whatever format you need - a good format could be JSON, since it can be used directly in javascript.

To pull data from the server down to javascript using jQuery, the following fetches makes an asynchronous request to http://youserver.com/my/uri and receives the data from the server in the supplied function.

```<code>$.get("my/uri",
    function(data) {
       // client side logic using the data from the server
    })
</code>```

Sending data from javascript to the server works similarly:

```<code>$.post("my/uri", { aValue : "put any data for the server here" }
    function(data) {
       // client side logic using the data returned from the server
    })
</code>```

Body:
I'd recommend having a look at jQuery. JQuery can be used to make AJAX calls back to the server, which can data back in whatever format you need - a good format could be JSON, since it can be used directly in javascript.

To pull data from the server down to javascript using jQuery, the following fetches makes an asynchronous request to http://youserver.com/my/uri and receives the data from the server in the supplied function.

$.get("my/uri",
    function(data) {
       // client side logic using the data from the server
    })

Sending data from javascript to the server works similarly:

$.post("my/uri", { aValue : "put any data for the server here" }
    function(data) {
       // client side logic using the data returned from the server
    })


答:
Would you try to persuade your client that using object-oriented
  programming is much cleaner?

I think you need to educate yourself more on programming paradigms. Object-Oriented programmed code is not necessarily cleaner, and in fact, it is not universally applicable. Also, a good object-oriented coder knows how to do good work using a procedural/modular (With Functional and Declarative paradigms, it is a bit harder, but it should not be overly difficult for a good programmer to arrive - via reading and deduction - to an acceptable FP/Declarative solution.)

You almost never cannot, I repeat, you almost cannot have a good understanding of when and how to use Object Orientation without having a good understanding of procedural and modular programming. OO is a lot more than just declaring classes and inheritance hierarchies.

Or would you try to follow what he required and give him crappy code?

If you cannot write good code procedurally, I doubt you can write good code in an object-oriented manner. Period. I'm not trying to judge here, but this has to be asserted.

Object Orientation is an extension of procedural and modular programming. Object-Orientation simply gives you tools that, when used appropriately, give you better mechanisms with which to deal encapsulation, coupling, cohesion and code-reuse/extensibility issues.

But all those issues are not inherent and unique to OO. They exist in procedural/modular code (and in other paradigms for that matter.) This is the type of complexity issues that, at its very core, is paradigm-independent. If you cannot handle them without OO glue, then it's unlikely you can handle them with it.

=========

Going back to your original question, of whether to try to persuade your client. It depends. As poster Sean McMillan said, if the client is simply trying to micro-manage the development effort for some agenda (read, office politics), walk away. People who do that sabotage projects to blame someone else, or push a particular agenda. You do not want to be involved in that.

OTH, there might be other reasons for such a requirement. Many embedded shops, for right or wrong, choose to put a lot of constrains on what you can do with C++ (no virtual methods, no exceptions, for instance.) Some times it is done in a knee-jerking fashion. Some other times, there are valid technical reasons for doing so.

So you need to understand why the client wants to avoid OO code. And if you can surmise that there is no political agenda (no red flags), then you should do the professional thing to do, which is simply do the code procedurally/modular, and do  a good job at it.

There is really no excuse for delivering crappy code, independently of the programming paradigm. If you can't produce acceptable code with one paradigm, you most certainly cannot produce acceptable code in general.


问:
How often to release in Scrum sprint
How often to you release during a sprint. Only at the end of the sprint or every time a feature is ready. And how to you handle bugfix releases?</p>

答:
After a couple of weeks we found a good solution that fits our needs. We decide to release when ever we want. How we do that:

when ever someone decide to release the actual develop branch, he merge all changes in the master branch tagged it with new release number and pushed onto our staging system.

than our QA and all other teams get's a mail with an actual changelog and they test staging system

if they found bugs we fix them in the master, pushed it to staging and then merge the master back into develop branch

when the staging system passed the QA the master goes live

Thats it. We use git and maven as CI system and we have a good test coverage. Which is one of the reasons we can doit like this.

Title: How often to release in Scrum sprint


问:
Who can change the View in MVC?
I'm working on a thick client graph displaying and manipulation application.  I'm trying to apply the MVC pattern to our 3D visualization component.

Here is what I have for the Model, View, and Controller:

Model - The graph and it's metadata.  This includes vertices, edges, and the attributes of each.  It does not contain position information, icons, colors, or anything display related.

View - This would commonly be called a scene graph.  It includes the 3D display information, texture information, color information, and anything else that is related specifically to the visualization of the model.

Controller - The controller takes the view and displays it in a Window using OpenGL (but it could potentially be any 3D graphics package).

The application has various "layouts" that change the position of the vertices in the display.  For instance, one layout may arrange the vertices in a circle.

Is it common for these layouts to access and change the view directly?  Should they go through the Controller to access the View?  If they go through the Controller, should they just ask for direct access to the View or should each change go through the controller?

I realize this is a bit different from the standard MVC example where there a finite number of Views.  In this case, the View can change in an infinite number of ways.  Perhaps I'm shattering some basic principle of MVC here.

Thanks in advance!

答:
I'm most familiar with Microsoft's ASP.NET MVC implementation.  MVC does not apply separation at the level you describe.

Model is essentially a data layer model.  It's not directly tied to the database tables (bad practice), but it's close.

View is where the UI lies.  So if this is web, that would be HTML/JavaScript or really even C# (via razor in a View page...but you need to work with an MVC3 project for all that to make sense).  My point is that its about the layering, not the languages.  Windows based applications tend to use MVVM rather than MVC so I don't think there is a direct tie, but the UI is still basically the View.

The controller is the middle man between these two.

There's not a lot more to it. MVC at it's core is a simple design.

You also need a business layer that works closely with the controller in all but the most trivial projects.  MVC does not have a defined business layer and yes it is OK and normal to add your own.

Accessing from View > View directly is not something I've heard of anyone attempting to do, nor would I recommend it.  For maintainability, you should create parallel layers for specific tasks.  The view should be modified either by itself or by calls to the controller which in turn may call the model, business layer or some other intermediate layer.

Title: Who can change the View in MVC?


问:
Would you use UML if it kept stakeholders from requesting changes frequently?
As much as programmers hate to document their code/system and draw UML (especially, Sequencing, Activity and State machine diagrams) or other diagramming notation, would you agree to do it if it kept managers from requesting a "minor change" every couple of weeks?

IOW, would you put together visual models to document the system if it helped you demonstrate to managers what the effect of changes are and why it takes so long to implement them?

(Edited to help programmers understand what type of answer I'm looking for.)

2nd edit: Restating my question again, "Would you be willing to use some diagramming notation, against your better nature as a programmer, if it helped you manage change requests?"

This question isn't asking if there might be something wrong with the process. It's a given that there's something wrong with the process. Would you be willing to do more work to improve it?

答:
Reasons users will accept denying a change request:

It will cost more money, but they have to feel the impact (It's actually their money or comes from their budget or has to be approved).

It will delay the project.

They will have to give up another feature.

They are required to get involved more/spend more of their time with approval, testing, writing up request etc.

Someone convinced them it will do harm or make the application worse.

If they are involved in the creation, editing, review/approval of the UML, they may think twice about a request since they will have to "go through all that again." This is no different than if they have to write a formal request, update documentation/training materials, commit their time to test/review/approve, etc. These types of things are more tangible to them than code.

ContentLicense: CC BY-SA 2.5


答:
I would agree with @vincentcr, but would add one more environment to consider: the corporate network.

Here you are likely to find many dozens or hundreds of (potential) users with the exact same browser, plugins, fonts etc.  The additional factors @vincentcr suggests also fail here - IP addresses are likely to be the same if the users are behind a corporate firewall, as are the users' reported locations.

Even with mouse gestures and typing patterns factored in, I doubt if these techniques could be used to identify unique users with any form of security, and if you wanted user accounts to be able to survive the user changing browsers, you would have to back it up with a more traditional authentication system anyway.

Though as others have said, it may be somewhat useful in detecting spambots and the like.  For example, the WordPress plugin "Bad Behaviour" analyses HTTP headers (amongst other factors) in an attempt to detect spambots.


答: What you describe is more akin to MVP, Supervising Controller or Passive View.</p>

Title: Who can change the View in MVC?

Body:
I'm working on a thick client graph displaying and manipulation application.  I'm trying to apply the MVC pattern to our 3D visualization component.

Here is what I have for the Model, View, and Controller:

Model - The graph and it's metadata.  This includes vertices, edges, and the attributes of each.  It does not contain position information, icons, colors, or anything display related.

View - This would commonly be called a scene graph.  It includes the 3D display information, texture information, color information, and anything else that is related specifically to the visualization of the model.

Controller - The controller takes the view and displays it in a Window using OpenGL (but it could potentially be any 3D graphics package).

The application has various "layouts" that change the position of the vertices in the display.  For instance, one layout may arrange the vertices in a circle.

Is it common for these layouts to access and change the view directly?  Should they go through the Controller to access the View?  If they go through the Controller, should they just ask for direct access to the View or should each change go through the controller?

I realize this is a bit different from the standard MVC example where there a finite number of Views.  In this case, the View can change in an infinite number of ways.  Perhaps I'm shattering some basic principle of MVC here.

Thanks in advance!


问:
Is there any reason to use VARCHAR sizes rounded to a 128/256/4096 byte offset?
In database schema's, I often notice VARCHAR sizes are rounded to the byte offsets 128/256 or 4096. I've done it before as well, and the idea behind it was probably something with efficiency.

However, is there still a valid reason to do so nowadays?
I often use '50', '100' or '200' as VARCHAR sizes these days,
as they are more natural and typically also shown in validation checks to the user.

答:
In general there is no reason for those column lengths.  There will be no performance improvement of a varchar(100) column versus a varchar(128) column.

However, I would double check the database system you are using for further clarification on restrictions and other vendor specific caveats.

For example, here's a good example of a database system restriction for SQL Server:

http://msdn.microsoft.com/en-us/library/ms186981.aspx

The total length of the row is more important than individual column lengths.


问:
Struggling with the Single Responsibility Principle
Consider this example:

I have a website. It allows users to make posts (can be anything) and add tags that describe the post. In the code, I have two classes that represent the post and tags. Lets call these classes Post and Tag.

Post takes care of creating posts, deleting posts, updating posts, etc.
Tag takes care of creating tags, deleting tags, updating tags, etc.

There is one operation that is missing. The linking of tags to posts. I am struggling with who should do this operation. It could fit equally well in either class.

On one hand, the Post class could have a function that takes a Tag as a parameter, and then stores it in a list of tags. On the other hand, the Tag class could have a function that takes a Post as a parameter and links the Tag to the Post.

The above is just an example of my problem. I am actually running into this with multiple classes that are all similar. It could fit equally well in both. Short of actually putting the functionality in both classes, what conventions or design styles exist to help me solve this problem. I am assuming there has to be something short of just picking one?

Maybe putting it in both classes is the correct answer?

答:
Like the Pirate Code, the SRP is more of a guideline than a rule, and it's not even a particularly well-worded one. Most developers have accepted the redefinitions of Martin Fowler (in Refactoring) and Robert Martin (in Clean Code), suggesting that a class should only have one reason to change (as opposed to one responsibility).

It's a good, solid (excuse the pun) guideline, but it's almost as dangerous to get hung up on it as it is to ignore it.

If you can add a Post to a Tag and vice versa, you haven't broken the single-responsibility principle. Both still only have one reason to change -- if the structure of that object changes. Changing the structure of either one does not change the way it is added to the other, so you are not adding a new "responsibility" to it.

Your final decision should really be dictated by the functionality required on the front end. There will likely be a need to add a Tag to a Post at some point, so do something like the following:

```<code>// C-style-language pseudo-code
class Post {
    string _title;
    string _content;
    Date _date;
    List<Tag> _tags;

    Post(string title, string content) {
        _title = title;
        _content = content;
        _date = Now;
        _tags = new List<Tag>();
    }

    Tag[] getTags() {
        return _tags.toArray();
    }

    void addTag(Tag tag) {
        if (_tags.contains(tag)) {
            throw "Cannot add tag twice";
        }

        _tags.Add(tag);
        tag.referencePost(this);
    }

    // more stuff here, obviously
}

class Tag {
    string _name;
    List<Post> _posts;

    Tag(string name) {
        _name = name;
    }

    Post[] getPosts() {
        return _posts.toArray();
    }

    void referencePost(Post post) {
        if (!post.getTags().contains(this) || _posts.contains(post)) {
            throw "Only reference a post by calling Post.addTag()";
        }

        _posts.Add(post);
    }

    // more stuff here too
}
</code>```

If, later, you find a need to add Posts to Tags as well, just add an addPost method to the Tag class and a referenceTag method to the Post class. Obviously, I have named them differently so that you don't accidentally cause a stack overflow by calling addTag from addPost and addPost from addTag.

Body:
Like the Pirate Code, the SRP is more of a guideline than a rule, and it's not even a particularly well-worded one. Most developers have accepted the redefinitions of Martin Fowler (in Refactoring) and Robert Martin (in Clean Code), suggesting that a class should only have one reason to change (as opposed to one responsibility).

It's a good, solid (excuse the pun) guideline, but it's almost as dangerous to get hung up on it as it is to ignore it.

If you can add a Post to a Tag and vice versa, you haven't broken the single-responsibility principle. Both still only have one reason to change -- if the structure of that object changes. Changing the structure of either one does not change the way it is added to the other, so you are not adding a new "responsibility" to it.

Your final decision should really be dictated by the functionality required on the front end. There will likely be a need to add a Tag to a Post at some point, so do something like the following:

// C-style-language pseudo-code
class Post {
    string _title;
    string _content;
    Date _date;
    List<Tag> _tags;

    Post(string title, string content) {
        _title = title;
        _content = content;
        _date = Now;
        _tags = new List<Tag>();
    }

    Tag[] getTags() {
        return _tags.toArray();
    }

    void addTag(Tag tag) {
        if (_tags.contains(tag)) {
            throw "Cannot add tag twice";
        }

        _tags.Add(tag);
        tag.referencePost(this);
    }

    // more stuff here, obviously
}

class Tag {
    string _name;
    List<Post> _posts;

    Tag(string name) {
        _name = name;
    }

    Post[] getPosts() {
        return _posts.toArray();
    }

    void referencePost(Post post) {
        if (!post.getTags().contains(this) || _posts.contains(post)) {
            throw "Only reference a post by calling Post.addTag()";
        }

        _posts.Add(post);
    }

    // more stuff here too
}

If, later, you find a need to add Posts to Tags as well, just add an addPost method to the Tag class and a referenceTag method to the Post class. Obviously, I have named them differently so that you don't accidentally cause a stack overflow by calling addTag from addPost and addPost from addTag.


答:
No, not in both! It should be in one place.

What I find uneasing in your question is the fact that you say "Post takes care of creating posts, deleting posts, updating posts" and same for Tag. Well, that is not right. Post can only take care of updating, the same for Tag. Creating and deleting is the work of someone else, external to Post and Tag (let's just call it Store).

Good responsibility for Post is "knows its author, contents and date of last update".
Good responsibility for Tag is "knows its name and purpose (read: description)".
Good responsibility for Store is "knows all Posts and all Tags and can add, remove and search them".

If you look at these three participants, who is most naturally the one who should have the knowledge of Post-Tag relationship?

(for me, it is the Post, it seems natural that it "knows its tags"; reverse search (all posts for a tag) seems to be the job of the Store; though I may be mistaken)

Title: Struggling with the Single Responsibility Principle

Body:
Consider this example:

I have a website. It allows users to make posts (can be anything) and add tags that describe the post. In the code, I have two classes that represent the post and tags. Lets call these classes Post and Tag.

Post takes care of creating posts, deleting posts, updating posts, etc.
Tag takes care of creating tags, deleting tags, updating tags, etc.

There is one operation that is missing. The linking of tags to posts. I am struggling with who should do this operation. It could fit equally well in either class.

On one hand, the Post class could have a function that takes a Tag as a parameter, and then stores it in a list of tags. On the other hand, the Tag class could have a function that takes a Post as a parameter and links the Tag to the Post.

The above is just an example of my problem. I am actually running into this with multiple classes that are all similar. It could fit equally well in both. Short of actually putting the functionality in both classes, what conventions or design styles exist to help me solve this problem. I am assuming there has to be something short of just picking one?

Maybe putting it in both classes is the correct answer?


问:
How should I license code written for a startup without a contract?
I wrote a fair amount of code for a startup, but I haven't signed a contract before doing so.

The only document that I signed with them does not mention the fact that I have to pass the rights on the code to them, and after a consulting with a lawyer it seems that I own the full rights.

Now I want to preemptively correct this situation by giving them some sort of exclusive license.

Is there an existing license for closed-source, exclusive use that is used in these cases or I simply write somewhere "I grant exclusive license to use and modify this piece of code to FooBar-inc at the followings conditions: bla bla bla  signed me, them"?

答:
To provide a general answer for people in the United States, if you signed a document that said your work is a "work for hire", then the client owns the rights. Here is the definition of a "work for hire":

```<code>Statutory Definition

Section 101 of the copyright law defines a “work made for hire” as

1    a work prepared by an employee within the scope of his or her employment
or

2    a work specially ordered or commissioned for use as a contribution to a
collective work, as a part of a motion picture or other audiovisual work, as
a translation, as a supplementary work, as a compilation, as an instruc-
tional text, as a test, as answer material for a test, or as an atlas, if the parties
expressly agree in a written instrument signed by them that the work shall
be considered a work made for hire. For the purpose of the foregoing sen-
tence, a “supplementary work” is a work prepared for a publication as a sec-
ondary adjunct to a work by another author for the purpose of introducing,
concluding, illustrating, explaining, revising, commenting upon, or assisting
in the use of the other work, such as forewords, afterwords, pictorial illus-
trations, maps, charts, tables, editorial notes, musical arrangements, answer
material for tests, bibliographies, appendixes, and indexes; and an “instruc-
tional text” is a literary, pictorial, or graphic work prepared for publication
and intended to be used in systematic instructional activities.
</code>```

www.copyright.gov/circs/circ09.pdf

I am not a lawyer, this is not legal advice.

Body:
To provide a general answer for people in the United States, if you signed a document that said your work is a "work for hire", then the client owns the rights. Here is the definition of a "work for hire":

Statutory Definition

Section 101 of the copyright law defines a “work made for hire” as

1    a work prepared by an employee within the scope of his or her employment
or

2    a work specially ordered or commissioned for use as a contribution to a
collective work, as a part of a motion picture or other audiovisual work, as
a translation, as a supplementary work, as a compilation, as an instruc-
tional text, as a test, as answer material for a test, or as an atlas, if the parties
expressly agree in a written instrument signed by them that the work shall
be considered a work made for hire. For the purpose of the foregoing sen-
tence, a “supplementary work” is a work prepared for a publication as a sec-
ondary adjunct to a work by another author for the purpose of introducing,
concluding, illustrating, explaining, revising, commenting upon, or assisting
in the use of the other work, such as forewords, afterwords, pictorial illus-
trations, maps, charts, tables, editorial notes, musical arrangements, answer
material for tests, bibliographies, appendixes, and indexes; and an “instruc-
tional text” is a literary, pictorial, or graphic work prepared for publication
and intended to be used in systematic instructional activities.

www.copyright.gov/circs/circ09.pdf

I am not a lawyer, this is not legal advice.


问:
Why isn't literate programming mainstream?
Literate programming has good ideals. Why do you think that this isn't mainstream? It is because it has failed to deliver?</p>

答:
I came to literate programming the other way around - I dreamed having the code organized as it fits my mind, not as the compiler requires it. I found Leo almost ideal for this purpose. It also supports keeping track of files changed outside. These files do not have to contain any special markup, so I can use Leo for myself without any need for others in the team to know. This feature - "@shadow trees" - is very promising, although still bit buggy, needs more eyeballs.  And it also fixes the "oh no, everything in one big file" problem both by organizing everything into tree outline and by support for external files.

For me, contrary to the name, the "literate programming" is not about documentation at all. I don't have more documentation than before. It is about having structure that helps me to not become lost. I swear by it especially when managing behemoth JSP files (and that despite Leo was originally intended primarily for Python and it does not have support for JSP language - I have to split the file to Leo tree manually !).


问:
Handling deleted users - separate or same table?
The scenario is that I've got an expanding set of users, and as time goes by, users will cancel their accounts which we currently mark as 'deleted' (with a flag) in the same table.

If users with the same email address (that's how users log in) wish to create a new account, they can signup again, but a NEW account is created. (We have unique ids for every account, so email addresses can be duplicated amongst live and deleted ones).

What I've noticed is that all across our system, in the normal course of things we constantly query the users table checking the user is not deleted, whereas what I'm thinking is that we dont need to do that at all...! [Clarification1: by 'constantly querying', I meant that we have queries which are like: '... FROM users WHERE isdeleted="0" AND ...'. For example, we may need to fetch all users registered for all meetings on a particular date, so in THAT query, we also have FROM users WHERE isdeleted="0" - does this make my point clearer?]

```<code>(1) continue keeping deleted users in the 'main' users table
(2) keep deleted users in a separate table (mostly required for historical
    book-keeping)
</code>```

What are the pros and cons of either approach?

答:
To break the table in two would be the lamest thing imaginable.

Here are the two very simple steps that I would recommend:

Rename the 'users' table to 'allusers'.

Create a view called 'users' as 'select * from allusers where deleted=false'.

P.S.
Sorry for the several-month-long delay in answering!


答:
While in theory things like that can go either way, in practice when you get down to the implementation one way is almost always a better fit than the other.  My hunch is it will fit better in the Post class because the association will be created during post creation or editing, when other things about the post are changing at the same time.

Also, if you are associating multiple tags and want to do it in one database update, you'd need to build some sort of list of all the tags associated with the same post before doing the update.  That list fits a lot better in the Post class.


答:
Theres an important detail missing from the equation.  Why does tag contain post and visa-versa?  The answer to this question determines the solution for each given set.

In general I can think of a situation that is similar.  A box and contents.   A box has contents so a has-a relationship is appropriate.  Can contents have a box?  Sure, a box with a box.  A box is contents.  But IS-A is not a good design for all boxes.   In such a case I would consider decorator pattern.  This way a box is decorated with contents at runtime as necessary.

Tags can have Posts too, but to me this is not a static relationship.  Rather it could be a report of all posts having said tag .  In this case its a new entity,  not has-a.


问:
Are there any resources on how to identify problems that could best be solved with templates?
I decided to improve my knowledge in template meta-programming. I know the syntax and rules and been playing with counteless examples from online resources.

I understand how powerful templates can be and how much compile time optimization they can provide but I still cant "think in templates", I can't seem to know by myself if a certain problem could be best solved with templates and if it can, how to adapt that problem to templates.

Is there some kind of online resource or book that teaches how to identify problems that could best be solved with templates and how to adapt that problem?

答:
Just today, I used templates to implement a Finite State Machine to lex some input. Expression templates are extremely powerful tools for implementing code concepts like that- they run like hand-optimized C++ and are obscenely fast, yet very generic and very easy to write.

Generally speaking, templates make the most sense when implementing generic algorithms. If you're not implementing a generic algorithm, they don't make that much sense.


答:
I see it as a valuable teaching tool, where a dissertation on code can be written, and then snippets of working code interleaved in it to instruct readers on the hows, whats, and whys of the code.

Outside a purely educational environment, I think only Knuth really understands how best to use it.

Title: Why isn't literate programming mainstream?

Body: Literate programming has good ideals. Why do you think that this isn't mainstream? It is because it has failed to deliver?</p>


问:
How can I convince cowboy programmers to use source control?
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?

答:
I hear your pain. I've walked into a couple of workplaces to find out there 'source control' was a shared folder on a network drive. The issue is generally not because they believe there approach is superior to anything else, it simply works and they have not ever been introduced to a workflow that successfully integrates source control.

With the flat earth team structure you have explained getting the change pushed from the top down may not be the best way to approach the situation. One method that is worth trying is to get buy in directly from one or two of the other devs to allow the concept to gather momentum. Once you have even one other dev on board it will be much easier to spread it to the remainder of the team. Slowly introduce them to the concept, say start working on a little side project, get it up and going in Git, or even branch something hosted on GitHub.

Start simple, introduce the concepts slowly and separately from their day to day workflow. Humans are great at learning things and adapting to change, especially when that change provides direct benefit to them (think evolution). However, when presented with a whole bunch of small changes at once it becomes alienating. Once they have a grasp of how source control works and the advantages it provides then try integrating it in a one of your internal project (if you start a new project, this is a wicked time to introduce it). Let the other projects function in the existing way if you like as well, this will be especially effective at highlighting advantages of decent code control.

If that fails, run.

ContentLicense: CC BY-SA 4.0


问:
Avoiding new operator in JavaScript -- the better way
Warning: This is a long post.

Let's keep it simple. I want to avoid having to prefix the new operator every time I call a constructor in JavaScript. This is because I tend to forget it, and my code screws up badly.

The simple way around this is this...

```<code>function Make(x) {
  if ( !(this instanceof arguments.callee) )
  return new arguments.callee(x);

  // do your stuff...
}
</code>```

But, I need this to accept variable no. of arguments, like this...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');
</code>```

The first immediate solution seems to be the 'apply' method like this...

```<code>function Make() {
  if ( !(this instanceof arguments.callee) )
    return new arguments.callee.apply(null, arguments);

  // do your stuff
}
</code>```

This is WRONG however -- the new object is passed to the apply method and NOT to our constructor arguments.callee.

Now, I've come up with three solutions. My simple question is: which one seems best. Or, if you have a better method, tell it.

First – use eval() to dynamically create JavaScript code that calls the constructor.

```<code>function Make(/* ... */) {
  if ( !(this instanceof arguments.callee) ) {
    // collect all the arguments
    var arr = [];
    for ( var i = 0; arguments[i]; i++ )
      arr.push( 'arguments[' + i + ']' );

    // create code
    var code = 'new arguments.callee(' + arr.join(',') + ');';

    // call it
    return eval( code );
  }

  // do your stuff with variable arguments...
}
</code>```

Second – Every object has __proto__ property which is a 'secret' link to its prototype object. Fortunately this property is writable.

```<code>function Make(/* ... */) {
  var obj = {};

  // do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // now do the __proto__ magic
  // by 'mutating' obj to make it a different object

  obj.__proto__ = arguments.callee.prototype;

  // must return obj
  return obj;
}
</code>```

Third – This is something similar to second solution.

```<code>function Make(/* ... */) {
  // we'll set '_construct' outside
  var obj = new arguments.callee._construct();

  // now do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // you have to return obj
  return obj;
}

// now first set the _construct property to an empty function
Make._construct = function() {};

// and then mutate the prototype of _construct
Make._construct.prototype = Make.prototype;
</code>```

eval solution seems clumsy and comes with all the problems of "evil eval".

__proto__ solution is non-standard and the "Great Browser of mIsERY" doesn't honor it.

The third solution seems overly complicated.

But with all the above three solutions, we can do something like this, that we can't otherwise...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');

m1 instanceof Make; // true
m2 instanceof Make; // true
m3 instanceof Make; // true

Make.prototype.fire = function() {
  // ...
};

m1.fire();
m2.fire();
m3.fire();
</code>```

So effectively the above solutions give us "true" constructors that accept variable no. of arguments and don't require new. What's your take on this.

-- UPDATE --

Some have said "just throw an error". My response is: we are doing a heavy app with 10+ constructors and I think it'd be far more wieldy if every constructor could "smartly" handle that mistake without throwing error messages on the console.

答:
How About This?

```<code>/* thing maker! it makes things! */
function thing(){
    if (!(this instanceof thing)){
        /* call 'new' for the lazy dev who didn't */
        return new thing(arguments, "lazy");
    };

    /* figure out how to use the arguments object, based on the above 'lazy' flag */
    var args = (arguments.length > 0 && arguments[arguments.length - 1] === "lazy") ? arguments[0] : arguments;

    /* set properties as needed */
    this.prop1 = (args.length > 0) ? args[0] : "nope";
    this.prop2 = (args.length > 1) ? args[1] : "nope";
};

/* create 3 new things (mixed 'new' and 'lazy') */
var myThing1 = thing("woo", "hoo");
var myThing2 = new thing("foo", "bar");
var myThing3 = thing();

/* test your new things */
console.log(myThing1.prop1); /* outputs 'woo' */
console.log(myThing1.prop2); /* outputs 'hoo' */

console.log(myThing2.prop1); /* outputs 'foo' */
console.log(myThing2.prop2); /* outputs 'bar' */

console.log(myThing3.prop1); /* outputs 'nope' */
console.log(myThing3.prop2); /* outputs 'nope' */
</code>```

EDIT: I forgot to add:

"If your app is truly 'heavy', the last thing you want is some overwrought construction mechanism to slow it down"

I absolutely agree - when creating 'thing' above without the 'new' keyword, it is slower/heavier than with it. Errors are your friend, because they tell you what's wrong. Moreover, they tell your fellow developers what they're doing wrong.

Body:
How About This?

/* thing maker! it makes things! */
function thing(){
    if (!(this instanceof thing)){
        /* call 'new' for the lazy dev who didn't */
        return new thing(arguments, "lazy");
    };

    /* figure out how to use the arguments object, based on the above 'lazy' flag */
    var args = (arguments.length > 0 && arguments[arguments.length - 1] === "lazy") ? arguments[0] : arguments;

    /* set properties as needed */
    this.prop1 = (args.length > 0) ? args[0] : "nope";
    this.prop2 = (args.length > 1) ? args[1] : "nope";
};

/* create 3 new things (mixed 'new' and 'lazy') */
var myThing1 = thing("woo", "hoo");
var myThing2 = new thing("foo", "bar");
var myThing3 = thing();

/* test your new things */
console.log(myThing1.prop1); /* outputs 'woo' */
console.log(myThing1.prop2); /* outputs 'hoo' */

console.log(myThing2.prop1); /* outputs 'foo' */
console.log(myThing2.prop2); /* outputs 'bar' */

console.log(myThing3.prop1); /* outputs 'nope' */
console.log(myThing3.prop2); /* outputs 'nope' */

EDIT: I forgot to add:

"If your app is truly 'heavy', the last thing you want is some overwrought construction mechanism to slow it down"

I absolutely agree - when creating 'thing' above without the 'new' keyword, it is slower/heavier than with it. Errors are your friend, because they tell you what's wrong. Moreover, they tell your fellow developers what they're doing wrong.


答:
The most common uses of templates are as follows:

```<code>std::vector<int> vec;
std::map<int, float> mymap;
</code>```

Then next common example is:

```<code>template<class T>
class MyArray {
public:
   virtual T get(int i) const=0;
};
</code>```

Together with this kind of usage:

```<code>class ArrayImpl : public MyArray<float> {
public:
     float get(int i) const { }
};
</code>```

That one showed important part of templates, which is type substitution -- T is replaced with float type in both places where it is used.

Title: Are there any resources on how to identify problems that could best be solved with templates?

Body:
I decided to improve my knowledge in template meta-programming. I know the syntax and rules and been playing with counteless examples from online resources.

I understand how powerful templates can be and how much compile time optimization they can provide but I still cant "think in templates", I can't seem to know by myself if a certain problem could be best solved with templates and if it can, how to adapt that problem to templates.

Is there some kind of online resource or book that teaches how to identify problems that could best be solved with templates and how to adapt that problem?

Body:
The most common uses of templates are as follows:

std::vector<int> vec;
std::map<int, float> mymap;

Then next common example is:

template<class T>
class MyArray {
public:
   virtual T get(int i) const=0;
};

Together with this kind of usage:

class ArrayImpl : public MyArray<float> {
public:
     float get(int i) const { }
};

That one showed important part of templates, which is type substitution -- T is replaced with float type in both places where it is used.


答:
I don't recall whether it was a DBMS or compiler, but I do recall (a long time ago) learning to use powers of 2 for array and column lengths.  There was a justification that it was 'faster' because of the implementation could use bit shifting. Whether holds true anymore is an open question. Anyone have any idea on whether it is still valid?

BTW I've moved column widths to uniform number b/c it is strange to tell users the char limit is 256 chars.

And some very old databases did limit you to 256 char-width columns.

Title: Is there any reason to use VARCHAR sizes rounded to a 128/256/4096 byte offset?

Body:
In database schema's, I often notice VARCHAR sizes are rounded to the byte offsets 128/256 or 4096. I've done it before as well, and the idea behind it was probably something with efficiency.

However, is there still a valid reason to do so nowadays?
I often use '50', '100' or '200' as VARCHAR sizes these days,
as they are more natural and typically also shown in validation checks to the user.


问:
How can one find out if open-source code was used in a commercial product?
Some open source licenses don't allow its usage in commercial products, but I bet some people/companies use it anyways.

Is it possible to prove that a closed source, commercial product illegally incorporates open source code? If so, how?

Example: Say Microsoft just gets the Linux kernel, slaps a new GUI on top of it and calls it "Windows 9." Would it be possible to prove they did this?

答: Under Unix, you can run the strings program to see if any strings from your code (error messages or string constants) show up.  Or you can look at the symbol table (assuming that it hasn't been stripped) to see if any of your module or routine names appear.  If you really want to be hard-core, you can track down a symbol (say a function name) and disassemble the executable at that point and see if the compiled code matches yours.  It's not easy (unless there are some tools or techniques I don't know about, which is entirely possible), but it's not impossible.


答:
Obviously, open source code is sometimes used in commercial products in violation of the license.

For example, here is a list someone linked to recently, of commercial products that violated the license on open source video projects.

Sometimes the offenders get found out, either by examination of their product, or by whistle-blowing, and lawsuits and backdowns result. Sometimes, no doubt, they get away with it.

But one thing to bear in mind: the bigger the company and the bigger the product, then the bigger the chance of it coming out, and the bigger the risks when it does. In your example, I reckon the chance would be close to absolute zero that Microsoft could rip off the Linux kernel to make Windows 9 without someone involved sounding the alarm. And the consequences would be disastrous.

Edit: In response to Joe Internet's comment, I was inferring from the tone of the question that NullUserException was talking about a situation where the usage was not in compliance with the GPL. In case he was misunderstanding this, of course the GPL is not an open source license which "[doesn't] allow its usage in commercial products." It would indeed be possible for Microsoft to release a Linux-based Windows 9 perfectly legally - although the requirement for them to make their source available would probably be quite unacceptable in their flagship OS product!

Title: How can one find out if open-source code was used in a commercial product?

Body:
Some open source licenses don't allow its usage in commercial products, but I bet some people/companies use it anyways.

Is it possible to prove that a closed source, commercial product illegally incorporates open source code? If so, how?

Example: Say Microsoft just gets the Linux kernel, slaps a new GUI on top of it and calls it "Windows 9." Would it be possible to prove they did this?


问:
Why is there still case sensitivity in some programming languages?
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.

答:
I like case sensitivity if for no other reason than it makes the code more self-documenting:

```<code>this is a CONSTANT
this is a ClassName
this is a methodName
this is a local variablename
</code>```

I typically program in Python, but back in my C# days, I found it very convenient to name class instances the same as the class, but lower (or camel) case (as others have said):

```<code>Thing thing = new Thing();
</code>```

Using case-insensitive languages requires some other convention for this, i.e., some sort of sigil like:

```<code>Thing oThing = new Thing()
Thing instanceOfThing = new Thing()
</code>```

Which is a "bad thing".

I also find it convenient to grep (case-sensitively) to find reference to a class vs. uses of a variable. With a case-insensitive language, this would be less easy. Same for search & replace.

Lastly, as a programmer, when I see words with different cases, it jumps out to me that they are different things...I rarely have bugs where variable cases were wrong, even in dynamic, scripted languages where a compiler would have helped.

Body:
I like case sensitivity if for no other reason than it makes the code more self-documenting:

this is a CONSTANT
this is a ClassName
this is a methodName
this is a local variablename

I typically program in Python, but back in my C# days, I found it very convenient to name class instances the same as the class, but lower (or camel) case (as others have said):

Thing thing = new Thing();

Using case-insensitive languages requires some other convention for this, i.e., some sort of sigil like:

Thing oThing = new Thing()
Thing instanceOfThing = new Thing()

Which is a "bad thing".

I also find it convenient to grep (case-sensitively) to find reference to a class vs. uses of a variable. With a case-insensitive language, this would be less easy. Same for search & replace.

Lastly, as a programmer, when I see words with different cases, it jumps out to me that they are different things...I rarely have bugs where variable cases were wrong, even in dynamic, scripted languages where a compiler would have helped.


问:
Organizing your Data Access Layer
I am using Entity Framework as my ORM in an ASP.Net application. I have my database already created so ended up generating the entity model from it. What is a good way to organize files/classes in the data access layer. My entity framework model is in a class library and I was planning on adding additional classes per Entity(i.e per database table) and putting all the queries related to those tables in their respective classes. I am not sure if this is a right approach and if it is then where do the queries requiring data from  multiple tables go?
Am I completely wrong in organizing my files based on entities/tables and should I organize them based on functional areas instead. </p>

答:
Here's a few ideas, I've seen and used in current & previous jobs.

Create a separate project something like "project name".Data

Create partial classes of your EF classes. Add static Get functions and a Save function derived from a base entity inheriting from EntityObject

Using a pattern like Unit Of work and storing the ObjectContext in the HTTPContext to handle your connections.

Link

http://aspmvc.co.cc/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-40/

Title: Organizing your Data Access Layer


问:
Sharing Authentication Across Subdomains using cookies
I know that in general cookies themselves are not considered robust enough to store authentication information.

What I am wondering is if there is an existing design pattern or framework for sharing authentication across subdomains without having to use something more complex like OpenID.

Ideally, the process would be that the user visits abc.example.org, logs in, and continues on to xyz.example.org where they are automatically recognized (ideally, the reverse should also be possible -- a login via xyz means automatic login at abc). The snag is that abc.example.org and xyz.example.org are both on different servers and different web application frameworks, although they can both use a shared database.

The web application platforms include PHP, ColdFusion, and Python (Django), although I'm also interested in this from a more general perspective (i.e. language agnostic).

答:
In general, you'll be storing some hashed value in your cookie, which will refer to some session store, server-side. The session will contain the authentication info, like a user key.

The pattern is to configure both apps to use the same:

parent domain for the session cookie

server-side session store

With ASP.NET and SQL Server, you can use the same SQL Server session store and set your session cookie domain in each app's web.config:

```<code><configuration>
    <system.web>
        <httpCookies domain=".example.org" />
        <sessionState
            mode="SQLServer"
            allowCustomSqlDatabase="true"
            sqlConnectionString="Data Source=localhost;Integrated Security=SSPI;Application Name=example"
            cookieless="false"
            timeout="20"
        />
    </system.web>
</configuration>
</code>```

Body:
In general, you'll be storing some hashed value in your cookie, which will refer to some session store, server-side. The session will contain the authentication info, like a user key.

The pattern is to configure both apps to use the same:

parent domain for the session cookie

server-side session store

With ASP.NET and SQL Server, you can use the same SQL Server session store and set your session cookie domain in each app's web.config:

<configuration>
    <system.web>
        <httpCookies domain=".example.org" />
        <sessionState
            mode="SQLServer"
            allowCustomSqlDatabase="true"
            sqlConnectionString="Data Source=localhost;Integrated Security=SSPI;Application Name=example"
            cookieless="false"
            timeout="20"
        />
    </system.web>
</configuration>


问:
Should back end processes be included in use cases in requirements document?
We're writing a requirements document for our client and need to include the use cases of the system. We're following this template:

```
ID
Description
Actors
Precondition
Basic Steps
Alternate Steps
Exceptions
Business validations/Rules
Postconditions
```

In the Basic Steps section, should we include steps that the system performs in the back end or should we only include steps that the user directly interacts with?

Example:

Basic Steps for Search 1:

```<code>User goes to search page
User enters term
User presses search
System matches search term with database entries
System displays results
</code>```

vs

Basic Steps for Search 2:

```<code>User goes to search page
User enters term
User presses search
System displays results
</code>```

答:
"steps that the user directly interacts with" is the definition of a use case.

Things the backend may (or may not do) are an appendix to the use case.  They're not testable, and they're not interactions.

A Use Case is defined pretty strictly to focus on testable behavior that's observable by one actor.

"description of steps or actions between a user (or "actor") and a software system which leads the user towards something useful"

If there's no interaction with the central actor, that means it's not part of the use case.

An appendix or supplement can be provided in case the algorithm is (a) important and (b) required and (c) known in advance.  This is rare, but can happen.

When there are complex interactions "behind the scenes", those are separate use cases with a separate collection of "behind the scenes" actors.  Other systems, generally, are other actors.

A user -- a person -- doesn't see or interact with the other systems.  They don't really exist.  The primary system could be providing results by magic.  Or they could be "canned" or static or computed in advance.

Another system -- also an actor -- doesn't see or interact with the user.  The primary system sends random requests for random reasons.


答:
In the project I'm working on now we're using ASP.NET MVC and Entity Framework 4.1. We also had a database first, but we went with the idea of using the POCO objects generated from the DBSet based T4 templates.

In our project, we've got one assembly called business which has a data namespace. Inside this namespace is where the DBContext and generated POCO's live. We don't touch this once the data access has been created. Now in addition, we have a set of repositories which we're using to; 1: run the basic CRUD needs and 2: create and deliver custom Data Transfer Objects up to the front end.

In the front end is where we're using the data annotations either on the custom DTO's or on custom ViewModels for specific needs. Our assumption is that we should validate the data coming from the front end as quickly as needed and then pass back clean models to the repositories. We're not really too worried about the entity change tracking or anything like that for entity framework so long as we save and pull successfully.

So far this has worked for us. Hope this helps you some, and good luck on your project.

Title: Organizing your Data Access Layer

Body:
I am using Entity Framework as my ORM in an ASP.Net application. I have my database already created so ended up generating the entity model from it. What is a good way to organize files/classes in the data access layer. My entity framework model is in a class library and I was planning on adding additional classes per Entity(i.e per database table) and putting all the queries related to those tables in their respective classes. I am not sure if this is a right approach and if it is then where do the queries requiring data from  multiple tables go?
Am I completely wrong in organizing my files based on entities/tables and should I organize them based on functional areas instead. </p>


问:
Does your company have a written policy about personal (technical) blogging?
Does your company have a written policy about personal (technical) blogging?

Care to share?

We encourage our developers to keep personal blogs and talk about technical problems they've encountered at work that are not core competency or core IP. We've been doing it "don't ask don't tell" style, but it's time to write something down.

Update: thank you all for your answers, we've implemented a policy for this last week - the full text is here.

答:
It is encouraged

We get 1 day a week for non-invoicable stuff such as learning, reading blogs, blogging, administration, preparing presentations for the weekly devcafés*, ...

Our boss prefers that we focus on sharing knowledge in that time.

We're actually building a dashboard for our intranet that will display the ratio "knowledge sharing / non-invoicable time".

* devcafés: dev team sits together 1 hour/week and 1 team member presents a new technology, methodology, ..


问:
How do regular expressions actually work?
Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool.

Is using a regular expression faster than parsing the file line by line and word by word looking for a match?  If so, how does it work?  How can you go faster than looking at each word?

答:
Why do you think they are quicker than searching the document?

There are some tricks you can do, eg. if you are searching for a 10letter word beginning with A and ending with B then if you find a A and the character 9 positions further on isn't B then you can skip some. see Knuth–Morris–Pratt algorithm


答:
Regular expressions just look fast because you have fast computers.

Back in the 1980's when 1 MIPS was a fast computer, regular expressions were a fairly big area of worry, concern and research because they were slow and ugly and compute intensive. Clever algorithm development followed and helped - but for all practical purposes these days you are seeing the miracle of fast machines papering over the cracks.

Title: How do regular expressions actually work?

Body:
Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool.

Is using a regular expression faster than parsing the file line by line and word by word looking for a match?  If so, how does it work?  How can you go faster than looking at each word?


答:
What makes a regular expression fast?

Actually, they're not. Not that much. It's just that they're not slow enough for most of us to notice. Back in the 'old slow days, it was much more noticeable.

They're also not the right tool for every job - the hammer.


问:
Controllers in CodeIgniter
I little bit new to the CodeIgniter framework and this is my first project with this framework. During a chat on StackOverflow somebody said that we need to make controllers tiny as possible.

Currently I have a default controller named home with 1332 lines of codes (and increasing) and a model named Profunction with 1356 lines of codes (and increasing).

The controller class have about 46 functions on it and also with model class.

I thought that Codeigniter can handle large Controllers or Models well, is there any problem/performance issue/security issues regarding this?

答:
About the "make controllers as tiny as possible", apparently the thin-controller-thick-model was being referred to there. This might help a bit, http://mikebernat.com/blog/MVC_-_Fat_Models_and_Skinny_Controllers_

46 functions in a class: Probably you are making one class do too many (possibly unrelated) things.

It is not about whether codeigniter can or cannot handle large models and controllers. It is about ease of maintenance for programmers. If you have one class doing many unrelated things, it will be difficult to read and understand. And anything that is difficult to understand will be difficult to modify.

Title: Controllers in CodeIgniter


答: RegEx's are comparably faster to code you might write because most libraries are the result of many developers spending many years optimizing them to squeak out every last bit of performance possible.  Its difficult for a single individual to duplicate that in their own search code.


答:
Your basic premise is wrong.

Regular expressions are not always faster than a simple search. It all depends on context. It depends on the complexity of the expression, the length of the document being searched, and a whole host of factors.

What happens is that the regular expression will be compiled into a simple parser (which takes time). Thus, if the document is small, this extra time will outweigh any advantage. Also, if the expression is simple, then the regular expression will not give you any advantage.

If the expression is complex and the document large enough, then you can gain some benefit. Whether this is significant enough to consider regular expressions to be faster will depend a lot on how much effort you want to put into the search (also regular expressions may have some optimizations that a library could provide that you would not have thought of yourself).

What I am trying to say is that there is no generalized, blanket answer. If you had a specific expression (and a known document size), then you could say derive a yes/no answer of whether the expression will be quicker than a simple search (and why).

The real advantage of regular expressions is that once you understand how to write them, the ability to express a complex search in a concise way. Because it is a generalized form, you can then build tools that allow searches in a way that is useful in the general case; it is usually at least as fast as a simple search (on documents of minimum size; on documents smaller than this it would not matter since even if it is slower, it is still fast enough).


答:
The purpose of the MVC pattern is to achieve separation of domain logic from the user interface, following the principle of Separation of Concerns:

In computer science, separation of concerns (SoC) is the process of separating a computer program into distinct features that overlap in functionality as little as possible. A concern is any piece of interest or focus in a program. Typically, concerns are synonymous with features or behaviors. Progress towards SoC is traditionally achieved through modularity of programming and encapsulation (or "transparency" of operation), with the help of information hiding. Layered designs in information systems are also often based on separation of concerns (e.g., presentation layer, business logic layer, data access layer, database layer).

While this is great and it's beautifully taken care of by CodeIgniter, it's not enough. The same principles apply to the individual components of the MVC triad (Model, View and Controller). Concerns should be as separate as possible, it's up to you to identify what those concerns are for your application, but if you put everything in one controller and one model you are probably doing it wrong.

The MVC pattern dictates that the controller's only job should be:

The controller receives user input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and a view port to perform actions based on that input.

So it shouldn't be that fat. It's job is to accept input, validate it and pass it on to the model and / or the view. As an oversimplification on what the concerns might be:

A controller should vaguely represent a page in your website,

A model should represent a table in your database.

So a controller should be concerned for one page and a model for one table. If your website has other pages than home, let's say a contact page then you should consider a page controller. That way it will be a lot easier for you to mentally connect parts of your application with the actual code, and greatly help with maintenance. By separating code in smaller logical parts, your code will be more robust and easier to test as per the Single Responsibility principle:

In object-oriented programming, the single responsibility principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

The numbers you have in your question are a little much. I can't safely comment on whether what you are doing could be improved, you should post the actual code for peer-review at Code Review Stack Exchange.

There is a small performance issue as well. Everytime you use a class, the class is loaded fully. The overhead is minuscule, but worth noting.

Further reading:

MVC - thin controller idea - Codeigniter/Zend on StackOverflow,

MVC in PHP - fat model or fat controller? on StackOverflow,

What should go in CodeIgniter models? on StackOverflow,

Fat Models and Thin Controllers with the Zend Framework, on Mooduino

As suggested by @melee in the comments you should look into CodeIgniter helpers, as a better place to put a lot of commonly used functionality. You can easily create your own helpers and have some of your functions in them and not in your controllers. And you should learn about hooks to easily extend the framework core.

Title: Controllers in CodeIgniter

Body:
I little bit new to the CodeIgniter framework and this is my first project with this framework. During a chat on StackOverflow somebody said that we need to make controllers tiny as possible.

Currently I have a default controller named home with 1332 lines of codes (and increasing) and a model named Profunction with 1356 lines of codes (and increasing).

The controller class have about 46 functions on it and also with model class.

I thought that Codeigniter can handle large Controllers or Models well, is there any problem/performance issue/security issues regarding this?


问:
Converting Fortran 77 code to C#
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?

答:
In my experience, a good way to go about this is to create a flow-chart of the Fortran code.  Try to separate out the targets of the GOTO statements into separate blocks, and use the diagram to try to understand the code on a high level.

See if you can logically replace the GOTOs with loops or function calls; if the resulting diagram is in the form of a tree-structure, it is relatively easy to convert to C# without resorting to GOTOs.  In the end though, you will need to understand the code intimately to be able to maintain and use the result with confidence.

Title: Converting Fortran 77 code to C#

OwnerDisplayName: Daniel B


问:
Single responsibility principle - am I overusing it?
For reference - http://en.wikipedia.org/wiki/Single_responsibility_principle

I have a test scenario where in one module of application is responsible for creating ledger entries. There are three basic tasks which could be carried out -

View existing ledger entries in table format.

Create new ledger entry using create button.

Click on a ledger entry in the table (mentioned in first pointer) and view its details in next page. You could nullify a ledger entry in this page.

(There are couple more operation/validations in each page but fore sake of brevity I will limit it to these)

So I decided to create three different classes -

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

These classes offer the services which could be carried out in those pages and Selenium tests use these classes to bring application to a state where I could make certain assertion.

When I was having it reviewed with on of my colleague then he was over whelmed and asked me to make one single class for all. Though I yet feel my design is much clean I am doubtful if I am overusing Single Responsibility principle

答: You only need one class, and the single responsibility of that class is to manage ledgers.


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
'Cross Examine' your client a bit (in a non-confrontational manner):

Does client actually know the difference between OOP and functional programming? Are client's concerns/requests legitimate?

If 'Yes':
    If you're qualified, do what they want and take your money. If you're not                qualified, tell them so and let them decide what to do.

Else:
    hi-tail it outta there!


答:
My company is completely oblivious to this.

I do have my own website, and another colleague has one too, but I think that's all. The colleague and I are the only two people who actively seek knowledge [as far as I know, although I think there are a few more, but low profile], so that may have something to do with it.

This may also be just a side-effect of our knowledge pool being nearly non-existent..as people here still focus on "superstar"/"hotshot" developers. Which sucks big-time.

My personal advice to you is: open up as much as possible.

Feedback is useful, and you'll get plenty of it by publishing stuff.

Body:
Does your company have a written policy about personal (technical) blogging?

Care to share?

We encourage our developers to keep personal blogs and talk about technical problems they've encountered at work that are not core competency or core IP. We've been doing it "don't ask don't tell" style, but it's time to write something down.

Update: thank you all for your answers, we've implemented a policy for this last week - the full text is here.


答:
There isn't a definitive implementation of the Single Responsibility Principle, or any other principle. You should decide based on what's more probable to change.

As @Karpie writes in an earlier answer:

You only need one class, and the single responsibility of that class is to manage ledgers.

That's an instinctual approach and it's probably correct, as what's more probable to change is the business logic of managing ledgers. If that happens, it'd be a lot easier to maintain one class than three.

But that should be examined and decided per case. You shouldn't really care for concerns with minuscule possibility of change and concentrate applying the principle on what's more likely to change. If the logic of managing ledgers is a multilayer process and layers are prone to change independently or are concerns that should be separate in principle (logic and presentation), then you should use separate classes. It's a game of probability.

A similar question on the subject of overusing design principles, that I think you'd find interesting: Design patterns: when to use and when to stop doing everything using patterns

Title: Single responsibility principle - am I overusing it?

Body:
For reference - http://en.wikipedia.org/wiki/Single_responsibility_principle

I have a test scenario where in one module of application is responsible for creating ledger entries. There are three basic tasks which could be carried out -

View existing ledger entries in table format.

Create new ledger entry using create button.

Click on a ledger entry in the table (mentioned in first pointer) and view its details in next page. You could nullify a ledger entry in this page.

(There are couple more operation/validations in each page but fore sake of brevity I will limit it to these)

So I decided to create three different classes -

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

These classes offer the services which could be carried out in those pages and Selenium tests use these classes to bring application to a state where I could make certain assertion.

When I was having it reviewed with on of my colleague then he was over whelmed and asked me to make one single class for all. Though I yet feel my design is much clean I am doubtful if I am overusing Single Responsibility principle


答:
A generic approach to "decompiling" such a code would be the following:

first compile it into a lower level form (e.g., LLVM)

perform an SSA-transform on it (it will help to clean up your local variables)

split the irreducible control flow (if any)

detect loops and ifs and replace them with the proper high level constructs

LLVM's own C backend can provide you with a first draft.

Title: Converting Fortran 77 code to C#

Body:
I'm trying to convert a Fortan77 program to C#. I have a subroutine with about 650 lines of code and horrific GOTO statements all over the place. I'm having a lot of trouble even starting to visualise the flow of the subroutine to figure out what it does.

Is there anybody with experience in this sort of thing who could give me any advice on how to get an overview of this subroutine? Are there some tools available to speed up or facilitate this type of conversion?