答:
who's usually responsible for use case analysis?

Everyone.

How usual is it to put a newbie on it?

Not too unusual.  You may have appropriate problem domain knowledge that makes you more valuable working with the users.

The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?

Yes.  They secretly want to destroy you.

No.  You've only been there a short time.

Title: Who usually does the use case analysis in the team?

Body:
I've just started my first IT job in a team with two developers (junior and senior), a project leader and an architect. My role is not yet completely defined and I said I'd be ok with both programming or testing. For now they put me on use case analysis since the PL says that it would leverage my analytical skills (I'm a science phd).

Now the question is who's usually responsible for use case analysis? How usual is it to put a newbie on it?

The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?


问:
Web pages in UML sequence diagrams?
In my current project, we have an ongoing discussion about whether or not it's a good idea to include an artifact representing a web page in an UML sequence diagram for a web application, making explicit which page starts a business interaction.

I think it's a bad idea to include a web page, for me a sequence diagram should be about business logic and the interactions between business objects, and not include presentation concerns such as web pages. If I were to include a web page it'd be in a navigation diagram. Also, in my experience I had not seen web pages included in sequence diagrams, up until now.

What's the recommendation/best practice on this? Should we include an artifact representing a web page in each of our sequence diagrams, or not?

EDIT :

It'd be ideal if the answers quoted design/modeling guidelines, books on UML, etc. arguing in favor or in opposition to including presentation artifacts in UML design diagrams. So far I haven't found an authoritative source that I can quote on the subject, instead of personal opinions.

答:
Web pages are part of the visual presentation of your final implementation, and are not part of any UML Sequence Diagram language construct.  Webpages would serve no purpose that is not alredy addressed within the current UML Sequence Diagram language and definition.

Additionally, by including a web page into any design document, you are presupposing a visual implementation.  If you are strictly designing sequence logic, you should have NO preconceived notions as to how the visual implementation might look.  (It's not a "website design diagram", it's a sequence-of-logic diagram.)

I find that you can almost always make a case to violate any guiding principle, design approach, teaming agreement, programming language paradigm, and even engineering "best practice".  But these are (and should be) "red flags" that alert you to the fact that you are going outside of the original concept/reason for using whatever technique/tool/etc. you've chosen, and it will only lead to less rigor.  Rigor, for its own sake, is not good or even necessary.  But rigor constraining behavior for a specific goal is usually "A Good Thing(tm)", because it saves you from yourself - or from "misuing" (of sorts) the framework that you've selected.

Suggestions/frameworks/best practices exist solely to advise and constrain your behavior in favor of a particular outcome, and are based upon the combined experience of many, many very talented people.  I don't recommend that you violate the UML Sequence Diagram construct by including webpages in the diagram, as this violates the rigor of the UML Sequence Diagram constructs, and it defeats some of its purpose (to remove visual - and other - considerations from what should be rather pure business logic and/or the interactions of your design).

I recommend that you stick to using the UML Sequence Diagram a little more literally - it's not a "website design diagram", unless THAT is what you WANT to make it.  And if so, you might call what you are making a "website sequence diagram", though it seems to be a stretch...

It's up to you to use your tools as they suit your needs.  But I wouldn't make this change lightly. =)

ContentLicense: CC BY-SA 3.0

Title: Web pages in UML sequence diagrams?


问:
C# Design, many properties, complex constructor and equality
I'm still a relative novice with OOP, so I am still trying to understand some of the best practices for how to design "good" objects.  I know this question is probably a rather subjective, which is why I am here rather than on stackoverflow.

I am designing an object that will have 20 separate string properties, none of which are required.  These constraints are fixed and cannot be changed as it is an implementation of an outside data source that I have no control over.

The design problem I am running into is how to effectively construct an instance of the object and be able to compare equality by comparing each field without violating normal best practices.

A 20 argument constructor seems very wrong, especially since every field is a string, and there are cases where many of them will be null.  I could use the optional arguments in C#4 to reduce the number of arguments that are actually called, but since everything is a string, I would have to use named parameters when calling the constructor, and that seems that it would be even uglier.

I have thought about trying to group the properties into smaller classes, but the most logical grouping still has an object with 10 properties, and at least half of the remaining properties have no logical grouping.

I could give each property a public setter, but that would make the object mutable, and thus complicate matters for overriding GetHashCode().  And I really don't need the object to be mutable.  Once it is built, there should never be a reason to change it, but I don't want to rely on that because who knows what someone will try to do with it.

Implementing IEquatable<T> is a possibility for the equality test, but my understanding is it is recommended to also override Equals(object obj) and GetHashCode() when implementing IEquatable so all Equals methods have the same behavior.

Is this an edge case where overriding Equals without overriding GetHashCode should be done?  I don't intend on using this object as a key in a dictionary or as a member of a HashSet, but I can't predict what someone else would try to do in the future.

Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own Compare() method?

Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method?

EDIT:
In response to Sign's comment, the purpose of the object is ultimately to be able to compare the data from the outside data source to our internal data to ensure it is accurate.  Both data sets contain address information, but they are broken up differently.

The internal data, is generally stored as a typical address (Street, City, State, Postal Code, County, Country), but there are variations when you have a suite/apartment # or a floor in a building.

The external data is broken down even further into smaller pieces.

So this object is supposed to be a common link between the 2 data sources and allow the user to compare like fields for equality.

EDIT #2:
Ultimately, I chose Doc Brown's answer because a modified version of his dictionary idea (with Enums as Keys instead of strings) was the simplest way to go without having a messy constructor and still provide the immutability I was hoping to have.  In the long term, I am going to experiment with some of Oliver's suggestions as some of his edits did have a lot to offer.

答:
Depends on requirements of course... By efficient you mean execution speed, or dev speed / clarity?

Here is another possibility:

Have your constructor take a class object as it's only parameter.  Certainly this "can" be easier to maintain and all the messy work to make it can be done elsewhere.  This is definitely advisable where clarity is more important so that every field has a logical name and it's not meshed into a dictionary that may not get built properly.  Who knows who will be working on your code next ;)  Or maybe it will be you 2 years from now and you can save time and mistakes?  But is that more important than execution speed? For me clarity trumps insignificant speed differences, up to a point where the accumulation is not insignificant of course ;)


问:
A free game-development language?
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.

答: FWIW, I purchased my cousin "Land of LISP" for this same purpose.  The book is illustrated with cartoons and is all about creating games in LISP.  My cousin only wanted to create text-based games, though, but I think the book will give him a good introduction to programming.</p>

Title: A free game-development language?


答: Looks like no one has thrown out Python+Pygame. Depending on your cousins age/maturity it certainly opens the possibility of a lot of cool stuff. That's certainly basic enough to get started, but with its huge standard libary, you can't really get bored with Python.</p>

Title: A free game-development language?

Body:
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.


问:
Who usually does the use case analysis in the team?
I've just started my first IT job in a team with two developers (junior and senior), a project leader and an architect. My role is not yet completely defined and I said I'd be ok with both programming or testing. For now they put me on use case analysis since the PL says that it would leverage my analytical skills (I'm a science phd).

Now the question is who's usually responsible for use case analysis? How usual is it to put a newbie on it?

The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?

答:
A few more thoughts:

```<code>who's usually responsible for use case analysis?
</code>```

It depends.  On a small team, often everyone.  I've also seen cases where the answer is

problem domain experts who don't write code

senior engineers - so the problem is defined by someone with experienced judgement

junior engineers - as a vehicle for getting their feet wet and communicating about the goals, the problems and the solutions before anyone runs too far down the road into implementation.

Another question might be - is it reasonable for anyone to be doing use case analysis right now.  It's "make work" if you already have a decent set of use cases sitting around that need to be implemented.  It's not make work if the team either (1) doesn't have a set of decent use cases, (2) is about to start a next release and doesn't have cases for that release.

```<code>How usual is it to put a newbie on it?
</code>```

Not too unusual. You may have appropriate problem domain knowledge that makes you more valuable working with the users.

I agree with S. Lott on this.

```<code>The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?
</code>```

Two weeks is early for that particular concern to be justifiable.

A few other questions to ask yourself (or your manager):

what does it take to see the code?  Can you just look at it and start learning it?  If it takes a special computer, or a special environment, or LAN access or something, it could be that you are doing use cases while the team waits for the buraucracy to do what needs doing.

is there someone free who can go through it with you?  If not, this may just be a bad time in the cycle for ramping up the new guy, so they have put you in a place where they know you can achieve some good stuff without much help.  This is realistic - I can say as a manager, I don't like the idea of just sending off a new guy (however skilled) with no support from an experienced team member.  If I have only two people and it's a crunch, I can't spare the 50% of the time that the senior guy will need to break in the new guy.  Seriously, it's usually 30-50% of a senior person's time for 2-4 weeks to get a new person up and going.  Learning curves are expensive.

I would say, it is unlikely that you need to be concered if - the team in a crunch, you don't have the tools you need, and/or the next release (for which you are writing use cases) is due to start immanently - they have put you ahead of the curve, so you are prepped and ready for a next release.

If you seem to be coming in in a long-term project where no new release is in sight, and no chaos is ensuing from bad use cases, then you may want to have a sit down with your manager in the next week or two and say "so... explain to me why writing use cases is beneficial?" and "couldn't I be more help testing or writing code?".  And then a real discussion of his perception of your skills vs. your perception and what you can do to get to the work you'd like to be doing.

Body:
A few more thoughts:

who's usually responsible for use case analysis?

It depends.  On a small team, often everyone.  I've also seen cases where the answer is

problem domain experts who don't write code

senior engineers - so the problem is defined by someone with experienced judgement

junior engineers - as a vehicle for getting their feet wet and communicating about the goals, the problems and the solutions before anyone runs too far down the road into implementation.

Another question might be - is it reasonable for anyone to be doing use case analysis right now.  It's "make work" if you already have a decent set of use cases sitting around that need to be implemented.  It's not make work if the team either (1) doesn't have a set of decent use cases, (2) is about to start a next release and doesn't have cases for that release.

How usual is it to put a newbie on it?

Not too unusual. You may have appropriate problem domain knowledge that makes you more valuable working with the users.

I agree with S. Lott on this.

The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?

Two weeks is early for that particular concern to be justifiable.

A few other questions to ask yourself (or your manager):

what does it take to see the code?  Can you just look at it and start learning it?  If it takes a special computer, or a special environment, or LAN access or something, it could be that you are doing use cases while the team waits for the buraucracy to do what needs doing.

is there someone free who can go through it with you?  If not, this may just be a bad time in the cycle for ramping up the new guy, so they have put you in a place where they know you can achieve some good stuff without much help.  This is realistic - I can say as a manager, I don't like the idea of just sending off a new guy (however skilled) with no support from an experienced team member.  If I have only two people and it's a crunch, I can't spare the 50% of the time that the senior guy will need to break in the new guy.  Seriously, it's usually 30-50% of a senior person's time for 2-4 weeks to get a new person up and going.  Learning curves are expensive.

I would say, it is unlikely that you need to be concered if - the team in a crunch, you don't have the tools you need, and/or the next release (for which you are writing use cases) is due to start immanently - they have put you ahead of the curve, so you are prepped and ready for a next release.

If you seem to be coming in in a long-term project where no new release is in sight, and no chaos is ensuing from bad use cases, then you may want to have a sit down with your manager in the next week or two and say "so... explain to me why writing use cases is beneficial?" and "couldn't I be more help testing or writing code?".  And then a real discussion of his perception of your skills vs. your perception and what you can do to get to the work you'd like to be doing.


答:
You probably won't find any discussions/advise either pro or con to adding webpages to UML Sequence Diagrams because one traditionally has never had anything to do with the other.

It sounds like your colleague(s) believe that your project's UML Sequence Diagram is lacking some level of information.

You might ask them to explain exactly what aspect of the project's design is "missing" from the diagram, such that they feel the need to represent it pictorally.  If you have them place this information into a bullet-list format, you might find that each bullet can (and should) be turned into a "standard/traditional component" of the UML Sequence Diagram.

That is to say, whatever information they feel is missing, and which should be represented visually, likely belongs as additional inputs/transitions/states/interactions within your diagram.

I suggest that you fix the diagram by adding the information that is currently missing from your diagram using traditional UML Sequence Diagram constructs, not by adding this missing information in the form of a pictograph.

Title: Web pages in UML sequence diagrams?

Body:
In my current project, we have an ongoing discussion about whether or not it's a good idea to include an artifact representing a web page in an UML sequence diagram for a web application, making explicit which page starts a business interaction.

I think it's a bad idea to include a web page, for me a sequence diagram should be about business logic and the interactions between business objects, and not include presentation concerns such as web pages. If I were to include a web page it'd be in a navigation diagram. Also, in my experience I had not seen web pages included in sequence diagrams, up until now.

What's the recommendation/best practice on this? Should we include an artifact representing a web page in each of our sequence diagrams, or not?

EDIT :

It'd be ideal if the answers quoted design/modeling guidelines, books on UML, etc. arguing in favor or in opposition to including presentation artifacts in UML design diagrams. So far I haven't found an authoritative source that I can quote on the subject, instead of personal opinions.


答:
Use cases usually come from someone who has a large amount of customer interaction, business knowledge, or a proper problem definition - not just the guy who had "the problem" explained to him.

Sticking anyone on Use Case analysis who does not fully understand the nature of the customer's need/complaint/requirements is bound to create a system that is not going to meet those needs/address those complaints or meet those requirements.

I think it is wrong to give Use Case development to anyone who doesn't have the COMPLETE problem/need definition in mind, and that it dooms a project to failure at the very outset.

If you don't have the knowledge that I mentioned, I'd suggest that the assignment must include a person/persons that have such knowledge, even if it will end up being you who codifies this knowledge into the Use Case representation on paper.


问:
How Much Logic in Getters
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?

答:
They tell me there should be as little logic as possible in getters and setters.

There needs to be as much logic as is necessary to fulfil the needs of the class. My personal preference is for as little as possible, but when maintaining code, you usually have to leave the original interface with the existing getters/setters, but put lots of logic in them to correct newer business logic (as an example, a "customers" getter in a post-911 environment has to meet "know your customer" and OFAC regulations, combined with a company policy prohibiting the appearance of customers from certain countries from appearing [such as Cuba or Iran]).

In your example, I prefer yours and dislike the "uncle bob" sample as the "uncle bob" version requires users/maintainers to remember to call loadStuff() before they call getStuff() - this is a recipe for disaster if any single one of your maintainers forgets (or worse, never knew). Most of the places I've worked in the past decade are still using code that is more than a decade old, so ease of maintenance is a critical factor to consider.

Title: How Much Logic in Getters

ContentLicense: CC BY-SA 4.0


问:
Version control programs for XML-files - merge/diff tool
My programming environment / language (gamemaker) gives the source files as "XML-files". Each resource has its own XML file. Where the properties (code is a property) are stored inside xml tags.

Is there a source control which can handle these? With subversion collisions don't seem to be handled correctly: when a collision happens, subversion breaks the XML structure. Which in turn breaks Gamemaker when updating.

EDIT (editing here as comments don't seem to handle newlines :P), an example of a source file that got "destroyed" by subversion:

```<code><object>
  <spriteName>sprBall</spriteName>
  <solid>0</solid>
  <visible>-1</visible>
  <depth>0</depth>
  <persistent>0</persistent>
<<<<<<< .mine
  <parentName>self</parentName>
=======
  <parentName>objExplosion</parentName>
>>>>>>> .r16
  <maskName><undefined></maskName>
  <events/>
</object>
</code>```

EDIT2: because of lack of experience with these tools, I asked the wrong question. So here a better wording:

In the example above an xml-file-reader will crash when trying to read the file. However manually resolving the conflict is "hard". (And in extreme cases impossible). "" doesn't say anything in itself. - As the first question becomes "parent name of what?"- An object? - which object? In this case one can see it quickly. However if the xml file reaches 100+ lines with 6-7 layers of tags it becomes a mess just looking through it. Especially as many tags are not named the same as they are in the IDE.

What I hoped to have is that the conflict to be changed in such a way an xml-reading library can read it. - For example that the .r16 change is displayed into a comment (or subtag/attribute).

```<code><parentName>self
<!--.r16: objExplosion--></parentName>
</code>```

From that point on I can program a tool to help analyzing the conflict. - I can use one of the many xml libraries to write a simple application visualizing the tree.

Well I'm just surprised this hasn't been a problem to anyone else :/.

答: Git has the concept of custom merge drivers for just this purpose.  It would allow you to merge xml files using your own algorithm instead of the default line-by-line.  However, to my knowledge no one has written one for xml and made it publicly available.  I don't know enough about subversion to know if it currently allows custom merge drivers, but since it is open source you can add it yourself.  Either way, it seems like a lot of work on a tool unless xml merging is a major productivity drain.


问:
Development of a bot/web crawler detection system
I am trying to build a system for my company which wants to check for unusual/abusive pattern of users (mainly web scrapers).

Currently the logic I have implemented parses the http access logs and takes into account the following parameters to calculate the potential of a user being a scraper or bot:

It checks v/s HTTP 'POST/GET' requests ratio for each IP

It calculates the ratio of unique URLs and total number of hits (sparsity) by each IP

Based on the above two parameters, we try to block any IP showing unusual behaviour, but these two parameters alone have not been sufficient for bot detection. Thus I would like to know:

Are there any other parameters which can be included to improve the detection?

I found a paper published in ACM library which follows the Bayesian approach to detect a crawler. Has anyone used this? How effective is this?

Stack Overflow and other high traffic sites have such kind of systems deployed, what logic do they follow to keep unwanted spammers/crawlers away in real time?

答:
I like requests-per-session-per-second, sessions-per-IP, and request pace over time.

The first - requests-per-session-per-second - will almost invaribly be different between humans and bots.

The second - sessions-per-IP - might appear to be easy to do, but you probably won't be able to tell the difference between a large number of users behind a NAT/firewall -and- a multithreaded bot.  It's probably a good "additonal indicator", however.

The third - request pace over time - requires a little explaining.  Bots tend to have their own analysis pace, processing "lag", and turnaround time between page requests.  Depending upon what they're doing, a bot can retrieve and parse tens-of-kilobytes of webpage content without flinching, and turn around and make yet another request.  However, this doesn't differ from what a human might do when, say, they immediately see a link they want, and click on it before the rest of the page loads.

However, a human - even one that frequently visits your site - will likely only remember how to quickly navigate the first few levels of your site using this method.  After a few levels, the human will likely "slow down", and read more content/take more time to process what they've requested.  A bot, on the other hand, will continue at their original pace throughout its entire interaction with your site.

Based upon this, I'd say any session that quickly (more-than-humanly-possible?) processes the retrieved content should be initially categorized a bot, but not cut off.  If, after two, perhaps three levels of navigation into your site the session still continues to make "faster-than-human" requests, definitively call it a bot, and cut it off.

If a human can actually achieve such a high and sustained interaction with your site, you probably have to redesign your site anyway (lol), and either give the user shortcuts to deep portions of your site, or "flatten" your site altogether.


问:
When can you call yourself good at language X?
This goes back to a conversation I've had with my girlfriend. I tried to tell her that I simply don't feel adequate enough in my programming language (C++) to call myself good. She then asked me, "Well, when do you consider yourself good enough?"

That's an interesting question. I didn't know what to tell her. So I'm asking you.

For any programming language, framework or the like, when do you reach a point were you sit back, look at what you've done and say, "Hey, I'm actually pretty good at this."? How do you define "good" so that you can tell others, honestly, "Yeah, I'm good at X".

Additionally, do you reach these conclusions by comparing what others can do?

Additional Info

I have read the canonical paper on how it takes ten-thousand hours before you are an expert on the field. (Props to anybody that knows what this paper is called again)

I have also read various articles from Coding Horror about interviewing people. Some people, it was said, "Cannot function outside of a framework." So they may be "good" for that framework, but not otherwise in the language. Is this true?

答: I often don't say that I'm good at X, but rather that I'm a quick learner and haven potential to be good at X.

ContentLicense: CC BY-SA 2.5


答: The language I got started with was Dark Basic Pro . I moved away from it kinda quick because game development isn't my cup of tea, but it was a powerful language. I haven't messed with it in quite a few years now so I'm not sure how good it is now(I last used it when DirectX 9 was new and cutting edge). But it allows you to quickly get started coding and making fancy 3D graphics with just a bit of code (and also, it's pure code.)</p>

Title: A free game-development language?


问:
How to do a login page for third party service without letting them sign on?
We have a unique situation (at least for me, first time seeing this).

We have a web form where accountants can fill in requests and that part is taken care of.  But after their login we redirect them to a third-party website where we need more information from them. The process is crazy right now since we have to give our account login info to all people filing with us.  So is there a way in PHP or any other solution where we can after that form on our website auto login with our information to that third party website in a way that our credentials are not visible to the users using the service?

答:
Your solution will mostly be dependent upon the workings of that third-party web site.

If they support some kind of third-party security like OpenAuth you may be able to use that.

Perhaps you can wrap their web site in your own code.  Do not redirect your user's browser to their site, but instead proxy the connection through your page.  Then you can intercept the login page and provide credentials without the end-user even knowing that there was a login.

Provide individual accounts on that third party site.  Probably not ideal, as now people have to manage their own credentials, but perhaps better than nothing.

Lastly, do be aware about the terms-of-service for the third-party site you are using.  Given you are using it as part of your workflow, do they allow for that?  Support it?  Explicitly disallow it such that you could find yourself cut off?


问:
Should I change author name in class file if I make more than 80% changes?
I am refactoring existing set of java test classes for automated UI tests.
At times I end up in making massive changes in class file or completely revamping it. This makes me think that when I am rewriting entire class then should I change author name in comment section to mine?

Am I being greedy? or is it going to be useful for one to see my name and ask me in case of doubts?

答:
I like seeing the original author's name, if only to find someone to start my quest for answers about the code.  (The author commonly has no recollection, but it's at least a shot!)

I would recommend that you simply add your name below the original author's.

There is no need to replace the other person's name, as they may know some aspect of the original business need that you don't, and others following after you might need to talk to that person as well.


答: In my opinion, Getters should not have a lot of logic in them. They should not have side effects and you should never get an exception from them. Unless of course, you know what you're doing. Most of my getters have no logic in them and just go to a field. But the notable exception to that was with a public API that needed to be as simple as possible to use. So I had one getter that would fail if another getter hadn't been called. The solution? A line of code like var throwaway=MyGetter; in the getter that depended upon it. I'm not proud of it, but I still do not see a cleaner way to do it

Title: How Much Logic in Getters

Body:
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?


答: The thing that thousands of people are developing games in is Flash. The "official" Flash development package from Adobe costs money, but there are free alternatives; FlashDevelop took me less than an hour to find, download, get running, and get a "Hello World" flash going. The Flixel library provides good supporting functions for games, including physics, particles, easy level creation for platformers, has lots of samples, and is easy to set up.

Title: A free game-development language?


答:
My policy on @author comments is:

If it's a brand new file, I put myself as the @author.

If it's an existing file, I leave @author alone, regardless of what I do to the file.

If you have questions on something, it doesn't matter who the @author of the file is - it matters who the @author of what portion of the file you're editing is. That's what [git/svn/whatever] blame is for.

IMO, @author needs to go away.

Title: Should I change author name in class file if I make more than 80% changes?

Body:
I am refactoring existing set of java test classes for automated UI tests.
At times I end up in making massive changes in class file or completely revamping it. This makes me think that when I am rewriting entire class then should I change author name in comment section to mine?

Am I being greedy? or is it going to be useful for one to see my name and ask me in case of doubts?


答:
Go with Unity3D...

there is no need to be afraid coding in it... and there is to much thing in that you don't need to code... samples will make your cousin happy.

also there are some videos... nice to be watched
walkerboystudio.com/html/unity_training_free.html

Title: A free game-development language?


问:
Is this a correct situation to use a constant?
So my professor was giving back some feedback on a project I've been working on. He docked a few marks for this code:

```<code>if (comboVendor.SelectedIndex == 0) {
  createVendor cv = new createVendor();
  cv.ShowDialog();
  loadVendors();
}
</code>```

This is in a combobox "index changed" handler. It's used when the user wants to create a new vendor, my top option (index 0, that never changes) opens the "Create a new Vendor" dialog. So the content of my combo box ends up looking like this:

```<code>Create New Vendor...
Existing Vendor
Existing Vendor 2
Existing Vendor 3
</code>```

His problem is with the first line code:

```<code>if (comboVendor.SelectedIndex == 0)
</code>```

He claims that the 0 should be a constant, and actually docked me marks because of that. He claims I shouldn't use literals in my code at all.

The thing is, I don't understand why I would want to make that code in that situation a constant. That index will never change, nor is it something that you would need to tweak. It seems like a waste of memory to keep a single 0 in memory that's used for a very specific situation and never changes.

答:
As others have said, you should use some method other than index number to identify the combo box item that corresponds to a given action; or, you can find the index with some programmatic logic and store that in a variable.

The reason I'm writing is to address your comment on the "use of memory".  In C#, as in most languages, constants are "folded" by the compiler.  For example, compile the following program, and examine the IL.  You'll find that all those numbers don't even make it into the IL, let alone the computer's memory:

```<code>public class Program
{
    public static int Main()
    {
        const int a = 1000;
        const int b = a + a;
        const int c = b + 42;
        const int d = 7928345;
        return (a + b + c + d) / (-a - b - c - d);
    }
}
</code>```

resulting IL:

```<code>.method public hidebysig static
    int32 Main () cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 CS$1$0000
    )

    IL_0000: nop
    IL_0001: ldc.i4.m1  // the constant value -1 to be returned.
    IL_0002: stloc.0
    IL_0003: br.s IL_0005

    IL_0005: ldloc.0
    IL_0006: ret
}
</code>```

So whether you use a constant, a literal, or a kilobyte of code using constant arithmetic, the value is treated literally in the IL.

A related point: Constant folding applies to string literals.  Many believe that a call like this causes too much needless, inefficient string concatenation:

```<code>public class Program
{
    public static int Main()
    {
        const string a = "a";
        const string b = a + a;
        const string c = "C";
        const string d = "Dee";
        return (a + b + c + d).Length;
    }
}
</code>```

But check out the IL:

```<code>IL_0000: nop
IL_0001: ldstr "aaaCDee"
IL_0006: callvirt instance int32 [mscorlib]System.String::get_Length()
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: ldloc.0
IL_000f: ret
</code>```

Bottom line: Operators on constant expressions result in constant expressions, and the compiler does all the computation; it doesn't affect run-time performance.

Body:
As others have said, you should use some method other than index number to identify the combo box item that corresponds to a given action; or, you can find the index with some programmatic logic and store that in a variable.

The reason I'm writing is to address your comment on the "use of memory".  In C#, as in most languages, constants are "folded" by the compiler.  For example, compile the following program, and examine the IL.  You'll find that all those numbers don't even make it into the IL, let alone the computer's memory:

public class Program
{
    public static int Main()
    {
        const int a = 1000;
        const int b = a + a;
        const int c = b + 42;
        const int d = 7928345;
        return (a + b + c + d) / (-a - b - c - d);
    }
}

resulting IL:

.method public hidebysig static
    int32 Main () cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 CS$1$0000
    )

    IL_0000: nop
    IL_0001: ldc.i4.m1  // the constant value -1 to be returned.
    IL_0002: stloc.0
    IL_0003: br.s IL_0005

    IL_0005: ldloc.0
    IL_0006: ret
}

So whether you use a constant, a literal, or a kilobyte of code using constant arithmetic, the value is treated literally in the IL.

A related point: Constant folding applies to string literals.  Many believe that a call like this causes too much needless, inefficient string concatenation:

public class Program
{
    public static int Main()
    {
        const string a = "a";
        const string b = a + a;
        const string c = "C";
        const string d = "Dee";
        return (a + b + c + d).Length;
    }
}

But check out the IL:

IL_0000: nop
IL_0001: ldstr "aaaCDee"
IL_0006: callvirt instance int32 [mscorlib]System.String::get_Length()
IL_000b: stloc.0
IL_000c: br.s IL_000e
IL_000e: ldloc.0
IL_000f: ret

Bottom line: Operators on constant expressions result in constant expressions, and the compiler does all the computation; it doesn't affect run-time performance.


问:
Javascript modularity, server based MVC & business reality
I understand this is a very broad question, but I have worked with various aspects of this problem individually and am struggling to bring all the concepts and technologies together.

I'd like to specify that answers should include these technologies:

C#

MVC 3 w/ Razor

Javascript w/jQuery

Anything above and beyond those (such as Backbone.js, Entity Framework, etc) are welcome as suggestions if they help answer the question which is:

Using the above listed technologies, what is an optimal strategy for organizing code and logic while maintaining scalability and the ability to create a rich, fast, clean UI?

Ideally the focus should be put on a solution being deployed in a business/corporate environment.  On that note, the technologies list above will not be changed so please don't offer solutions with "you should be using xxx instead of yyy that you are using now".

Background

I work with jQuery everyday, have adopted ASP.NET's MVC and have been working with C# for a long time.  So you can present solutions assuming intermediate-to-advanced knowledge of those technologies.

I'll organize the question into smaller parts to make it simpler to respond to:

1. Project structure

Given I am working with ASP.NET MVC (in Visual Studio 2010) I would like a directory structure solution that offers some acceptance of the main layout this type of application.  Something like Brunch I suppose, but with a little more detail of what each folder would contain and how it works with other areas of the app.

2. Data access

I'd like to modularize my data access as much as I can, with an API-type structure.  You can assume lots of POCO objects (User, UserGroup, Customer, OrderHeader, OrderDetails, etc), but there will also be some complex reports that require data intensive SQL and careful UI rendering.  EF + LINQ are fantastic for the former but not so much for the latter.  I can't find something that seems to fit both scenarios without being overly complicated or overly simple.

3. Client-Side Code Organization and UI Rendering

Like most developers first picking up jQuery, I fell into the trap of mashing together code wherever it needed to go but quickly found it piling up and turning ugly.  Although I've come leaps and bounds since then, I still struggle with modularizing my code and working with various parts of the UI without repeating code.

As an example, a typical piece of code I might write would look like this, I have commented the stuff that bothers me (note that I've since changed to using deferred AJAX calls and separated the actual data requests from the DOM manipulation):

```<code>$('#doSomethingDangerous').click(function () {
    // maybe confirm something first
    if (confirm('Are you sure you want to do this?')) {

        // show a spinner?  something global would be preferred so I don't have to repeat this on every page
        $('#loading').show();

        // maybe the page should notify the user of what's going on in addition to the dialog?
        $('#results').show().html('<h2>Please wait, this may take a while...</h2>');

        $.ajax({
            url: 'blah/DoDangerousThing',
            success: function (data) {
                // The results will be loaded to the DOM obviously, is there a better way to pull this type of specific code out of the data access calls?
                $('#results').empty();
                $('#results').append('<b>' + data.length + '</b> users were affected by this dangerous activity');
                $('#results').append('<ul>');

                // I've recently started to use jQuery templates for this sort of logic, is that the way to go?
                $(data).each(function (i, user) {
                    $('#results').append('<li>' + user.Username + '</li>');
                });
                $('#results').append('</ul>');

                // Need to hide the spinner, again would prefer to have this done elsewhere
                $('#loading').hide();
            }
        });
    }
});
</code>```

General Questions

Client MVC vs. server MVC?  My project is already a server-side MVC structure, so is there still a need for client MVC like Backbone.js provides?

Should Javascript files get created for each object (like an OrderHeader.js) and then minified/merged during the build?  Or should there just be an Order.js which has logic for OrderHeader, OrderDetails, Reports etc?

How should complex queries be handled?  Right now my leading theory is /Reports/Orders-By-Date/ or something along those lines and I use a custom SQL query that renders a custom dataset (or ViewModel) to the Razor View.  But what about paging, sorting, etc?  Is this better to be done client or server side?  (assume larger dataset - 2 to 3 second SQL query)

I've read through Microsoft's Project Silk.  Is this a good way to go?  How does it compare to Backbone.js or others?

I'm very accustomed to an N-tiered architecture, do these concepts somewhat throw that out the window?  It seems MVC is like a bunch of mini N-tiered sections within what would have been the front-end or top tier in the past.

Again the more specific your answers are the better they will be.  I've read a lot of high level documentation and examples, I'm trying to better understand translating it into real world examples.

答:
I'm not going to write a full answer, but want to share some tips.

My tips:

1. Project structure

I've found that the default MVC structure is not good for me. I generally work in the controller, views and model of the same entity (think product, order, customer) at the same time. So, I like to have the files in the same folder, but with different namespaces.

2. Data

If you go with Linq-to-SQL or EF you will regret later.

I use PetaPoco that allows me to run SQL retrieving and updating records without the mapping pain, but without learning a new way to do things and without the performance nightmares.

I have a code generator for creating the initial POCO class with the PetaPoco attributes, and then change the class when some field is added or removed.

PetaPoco works with dynamic and standard classes, so you don't have any compromises (Massive is all dynamic and Dapper all standard classes)

I also generate a master SQL, using the built in SqlBuilder, that contains all the standard joins for the entity, but no WHERE's so I reuse the same SQL for retrieving one entity or a list.

3. Jquery
You can standarize some parts of the UI using a general jQuery call (stuffing some data inside the HTML element).

For example, I have this for deleting.

```<code>var deleteLinkObj;
// delete Link
$('.jbtn-borrar').click(function () {
    deleteLinkObj = $(this);  //for future use
    $('#delete-dialog').dialog('open');
    return false; // prevents the default behaviour
});
$('#delete-dialog').dialog({
    autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
    buttons: {
        "Borrar": function () {
            $.post(deleteLinkObj[0].href, function (data) {  //Post to action
                if (data == 'OK') {
                    deleteLinkObj.closest("tr").hide('fast'); //Hide Row
                }
                else {
                    alert(data);
                }
            });
            $(this).dialog("close");
        },
        "Cancelar": function () {
            $(this).dialog("close");
        }
    }
});
</code>```

I just need to add the class jbtn-borrar to a hyperlink, and it shows a dialog, delete the record and hide the tr

But don't overthink it. Your app will shine with the small touches in every view.

Client MVC vs. server MVC

Server MVC. Take advantage of partial views that you can use in initial rendering and refresh some parts with Ajax using the same view. See this excellent article

How should complex queries be handled (lets call it a Report)

I use a class that have the Report parameters as properties (handy for using MVC automapping) and a Generate method that executes the query and fill a List of a custom class (if you don't have a class that fit the ViewModel)

You can use this class as the model of the view and fill the table with the generated list.

Microsoft's Project Silk

Overarchitected. Run as fast as you can in the opposite direction.

OwnerDisplayName: TerryR

Body:
I'm not going to write a full answer, but want to share some tips.

My tips:

1. Project structure

I've found that the default MVC structure is not good for me. I generally work in the controller, views and model of the same entity (think product, order, customer) at the same time. So, I like to have the files in the same folder, but with different namespaces.

2. Data

If you go with Linq-to-SQL or EF you will regret later.

I use PetaPoco that allows me to run SQL retrieving and updating records without the mapping pain, but without learning a new way to do things and without the performance nightmares.

I have a code generator for creating the initial POCO class with the PetaPoco attributes, and then change the class when some field is added or removed.

PetaPoco works with dynamic and standard classes, so you don't have any compromises (Massive is all dynamic and Dapper all standard classes)

I also generate a master SQL, using the built in SqlBuilder, that contains all the standard joins for the entity, but no WHERE's so I reuse the same SQL for retrieving one entity or a list.

3. Jquery
You can standarize some parts of the UI using a general jQuery call (stuffing some data inside the HTML element).

For example, I have this for deleting.

var deleteLinkObj;
// delete Link
$('.jbtn-borrar').click(function () {
    deleteLinkObj = $(this);  //for future use
    $('#delete-dialog').dialog('open');
    return false; // prevents the default behaviour
});
$('#delete-dialog').dialog({
    autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
    buttons: {
        "Borrar": function () {
            $.post(deleteLinkObj[0].href, function (data) {  //Post to action
                if (data == 'OK') {
                    deleteLinkObj.closest("tr").hide('fast'); //Hide Row
                }
                else {
                    alert(data);
                }
            });
            $(this).dialog("close");
        },
        "Cancelar": function () {
            $(this).dialog("close");
        }
    }
});

I just need to add the class jbtn-borrar to a hyperlink, and it shows a dialog, delete the record and hide the tr

But don't overthink it. Your app will shine with the small touches in every view.

Client MVC vs. server MVC

Server MVC. Take advantage of partial views that you can use in initial rendering and refresh some parts with Ajax using the same view. See this excellent article

How should complex queries be handled (lets call it a Report)

I use a class that have the Report parameters as properties (handy for using MVC automapping) and a Generate method that executes the query and fill a List of a custom class (if you don't have a class that fit the ViewModel)

You can use this class as the model of the view and fill the table with the generated list.

Microsoft's Project Silk

Overarchitected. Run as fast as you can in the opposite direction.

OwnerDisplayName: Eduardo Molteni


答:
TerryR my friend, you and I should have a drink. We have some similar problems.

1. Project Structure: I agree with Eduardo that the folder structure in an MVC app leaves something to be desired. You have your standard Controllers, Models, and Views folders. But then the Views folder gets broken down into a different folder for each Controller, plus a Shared folder. And each Views/ControllerName or Views/Shared can be broken down into EditorTemplates and DisplayTemplates. But it lets you decide how to organize your Models folder (you can do with or without subfolders & additional namespace declarations).

God forbid you are using Areas, which duplicate the Controllers, Models, and Views folder structure for each area.

```<code>/Areas
    /Area1Name
        /Controllers
            FirstController.cs
            SecondController.cs
            ThirdController.cs
        /Models
            (can organize all in here or in separate folders / namespaces)
        /Views
            /First
                /DisplayTemplates
                    WidgetAbc.cshtml <-- to be used by views in Views/First
                /EditorTemplates
                    WidgetAbc.cshtml <-- to be used by views in Views/First
                PartialViewAbc.cshtml <-- to be used by FirstController
            /Second
                PartialViewDef.cshtml <-- to be used by SecondController
            /Third
                PartialViewMno.cshtml <-- to be used by ThirdController
            /Shared
                /DisplayTemplates
                    WidgetXyz.cshtml <-- to be used by any view in Area1
                /EditorTemplates
                    WidgetXyz.cshtml <-- to be used by any view in Area1
                PartialViewXyz.cshtml <-- to be used anywhere in Area1
            _ViewStart.cshtml <-- area needs its own _ViewStart.cshtml
            Web.config <-- put custom HTML Helper namespaces in here
        Area1NameRegistration.cs <-- define routes for area1 here
    /Area2Name
        /Controllers
        /Models
        /Views
        Area2NameRegistration.cs <-- define routes for area2 here

/Controllers
    AccountController.cs
    HomeController.cs
/Models
/Views
    /Account
        /DisplayTemplates
            WidgetGhi.cshtml <-- to be used views in Views/Account
        /EditorTemplates
            WidgetGhi.cshtml <-- to be used views in Views/Account
        PartialViewGhi.cshtml <-- to be used by AccountController
    /Home
        (same pattern as Account, views & templates are controller-specific)
    /Shared
        /DisplayTemplates
            EmailAddress.cshtml <-- to be used by any view in any area
            Time.cshtml <-- to be used by any view in any area
            Url.cshtml <-- to be used by any view in any area
        /EditorTemplates
            EmailAddress.cshtml <-- to be used by any view in any area
            Time.cshtml <-- to be used by any view in any area
            Url.cshtml <-- to be used by any view in any area
        _Layout.cshtml <-- master layout page with sections
        Error.cshtml <-- custom page to show if unhandled exception occurs
    _ViewStart.cshtml <-- won't be used automatically in an area
    Web.config <-- put custom HTML Helper namespaces in here
</code>```

This means if you are working with something like a WidgetController, you have to look in other folders to find the related WidgetViewModels, WidgetViews, WidgetEditorTemplates, WidgetDisplayTemplates, etc. As cumbersome as this may be, I stick to it and don't deviate from these MVC conventions. As far as putting a model, controller, and view in the same folder but with different namespaces, I avoid this because I use ReSharper. It will squiggly underline a namespace that doesn't match the folder where the class is located. I know I could turn this R# feature off, but it helps in other parts of the project.

For non-class files, MVC gives you Content and Scripts out of the box. We try to keep all of our static / non-compiled files in these places, again, to follow convention. Any time we incorporate a js library that uses themes (images and or css), the theme files all go somewhere under /content. For script, we just put all of them directly into /scripts. Originally this was to get JS intellisense from VS, but now that we get JS intellisense from R# regardless of placement in /scripts, I suppose we could deviate from that and divide scripts by folder to better organize. Are you using ReSharper? It is pure gold IMO.

Another little piece of gold that helps a lot with refactoring is T4MVC. Using this, we don't need to type in string paths for area names, controller names, action names, even files in content & scripts. T4MVC strongly types all of the magic strings for you. Here's a small sample of how your project structure doesn't matter as much if you're using T4MVC:

```<code>// no more magic strings in route definitions
context.MapRoutes(null,
    new[] { string.Empty, "features", "features/{version}" },
    new
    {
        area = MVC.PreviewArea.Name,
        controller = MVC.PreviewArea.Features.Name,
        action = MVC.PreviewArea.Features.ActionNames.ForPreview,
        version = "december-2011-preview-1",
    },
    new { httpMethod = new HttpMethodConstraint("GET") }
);

@* T4MVC renders .min.js script versions when project is targeted for release *@
<link href="@Url.Content(Links.content.Site_css)?r=201112B" rel="stylesheet" />
<script src="@Url.Content(Links.scripts.jquery_1_7_1_js)" type="text/javascript">
</script>

@* render a route URL as if you were calling an action method directly *@
<a href="@Url.Action(MVC.MyAreaName.MyControllerName.MyActionName
    (Model.SomeId))">@Html.DisplayFor(m => m.SomeText)</a>

// call action redirects as if you were executing an action method
return RedirectToAction(MVC.Area.MyController.DoSomething(obj1.Prop, null));
</code>```

2. Data access: I have no experience with PetaPoco, but I'm sure it's worth checking out. For your complex reports, have you considered SQL Server Reporting services? Or, are you running on a different db? Sorry I'm not clear on what exactly you are asking for. We use EF + LINQ, but we also put certain knowledge about how to generate reports in domain classes. Thus, we have controller call domain service call repository, instead of having controller call repository directly. For ad-hoc reports we use SQL Reporting Services, which again isn't perfect, but our users like to be able to bring data into Excel easily, and SSRS makes that easy on us.

3.  Client-Side Code Organization and UI Rendering: This is where I think I may be able to offer some help. Take a page from the book of MVC unobtrusive validation and unobtrusive AJAX. Consider this:

```<code><img id="loading_spinner" src="/path/to/img" style="display:none;" />
<h2 id="loading_results" style="display:none;">
    Please wait, this may take a while...
</h2>
<div id="results">
</div>
<input id="doSomethingDangerous" class="u-std-ajax"
    type="button" value="I'm feeling lucky"
    data-myapp-confirm="Are you sure you want to do this?"
    data-myapp-show="loading_spinner,loading_results"
    data-myapp-href="blah/DoDangerousThing" />
</code>```

Ignore the ajax success function for now (more on this later). You can get away with a single script for some of your actions:

```<code>$('.u-std-ajax').click(function () {
    // maybe confirm something first
    var clicked = this;
    var confirmMessage = $(clicked).data('myapp-confirm');
    if (confirmMessage && !confirm(confirmMessage )) { return; }

    // show a spinner?  something global would be preferred so
    // I dont have to repeat this on every page
    // maybe the page should notify the user of what's going on
    // in addition to the dialog?
    var show = $(clicked).data('myapp-show');
    if (show) {
        var i, showIds = show.split(',');
        for (i = 0; i < showIds.length; i++) {
            $('#' + showIds[i]).show();
        }
    }

    var url = $(clicked).data('myapp-href');
    if (url) {
        $.ajax({
            url: url,
            complete: function () {
                // Need to hide the spinner, again would prefer to
                // have this done elsewhere
                if (show) {
                    for (i = 0; i < showIds.length; i++) {
                        $('#' + showIds[i]).hide();
                    }
                }
            }
        });
    }
});
</code>```

The above code will take care of the confirmation, showing the spinner, showing the wait message, and hiding the spinner / wait message after the ajax call is complete. You configure the behaviors using data-* attributes, like the unobtrusive libraries.

General Questions

- Client MVC vs. server MVC? I didn't try to librarify the actions you took in the success function because it looks like your controller is returning JSON. If your controllers are returning JSON, you might want to look at KnockoutJS. Knockout JS version 2.0 was released today. It can plug right into your JSON, so that an observable click can automatically bind data to your javascript templates. On the other hand if you don't mind having your ajax action methods return HTML instead of JSON, they can return the already-constructed UL with its LI children, and you can append that to an element by using data-myapp-response="results". Your success function would then just look like this:

```<code>success: function(html) {
    var responseId = $(clicked).data('myapp-response');
    if (responseId) {
        $('#' + responseId).empty().html(html);
    }
}
</code>```

To sum up my best answer for this, if you must return JSON from your action methods, you are skipping the server-side View, so this really isn't server MVC -- it's just MC. If you return PartialViewResult with html to ajax calls, this is server MVC. So if your app must return JSON data for ajax calls, use client MVVM like KnockoutJS.

Either way, I don't like the JS you posted because it mixes your layout (html tags) with behavior (asynchronous data load). Choosing either server MVC with partial html views or client MVVM with pure JSON viewmodel data will solve this problem for you, but manually constructing DOM/HTML in javascript violates separation of concerns.

- Javascript file creation Apparently minification features are coming in .NET 4.5. If you go the unobtrusive route, there shouldn't be anything stopping you from loading all of your JS in 1 script file. I would be careful about creating different JS files for each entity type, you will end up with JS file explosion. Remember, once your script file is loaded, the browser should cache it for future requests.

- Complex queries I don't consider having feature like pagination, sorting, etc, as being complex. My preference is to handle this with URL's and server-side logic, to make the db queries as limited as needed. However we are deployed to Azure, so query optimization is important to us. For example: /widgets/show-{pageSize}-per-page/page-{pageNumber}/sort-by-{sortColumn}-{sortDirection}/{keyword}. EF and LINQ to Entities can handle pagination and sorting with methods like .Take(), .Skip(), .OrderBy(), and .OrderByDescending(), so you get what you need during the db trip. I haven't found the need for a clientlib yet, so I honestly don't know much about them. Look to other answers for more advice on that.

- Project silk Never heard of this one, will have to check it out. I am a big fan of Steve Sanderson, his books, his BeginCollectionItem HtmlHelper, and his blog. That said, I don't have any experience with KnockoutJS in production. I have checked out its tutorials, but I try not to commit to something until it's at least version 2.0. Like I mentioned, KnockoutJS 2.0 was just released.

- N-tier If by tier you mean different physical machine, then no, I don't think anything goes out any windows. Generally 3-tier means you have 3 machines. So you might have a fat client as your presentation tier, that runs on a user's machine. The fat client might access a service tier, that runs on an application server and returns XML or whatever to the fat client. And the service tier might get its data from a SQL server on a 3rd machine.

MVC is one layer, on 1 tier. Your controllers, models, and views are all part of your Presentation Layer, which is 1 tier in the physical architecture. MVC implements the Model-View-Controller pattern, which is where you might be seeing additional layers. However, try not to think of these 3 aspects as tiers or layers. Try to think of all 3 of them as Presentation Layer Concerns.

Update after pres/bus/data comment

Okay, so you are using tier and layer interchangably. I usually use the term "layer" for logical / project / assembly divisions, and tier for physical network separation. Sorry for the confusion.

You will find quite a few people in the MVC camp who say you should not use the "Models" in MVC for your entity data model, nor should you use your Controllers for business logic. Ideally your models should be view-specific ViewModels. Using something like Automapper, you take your entities from your domain model and DTO them into ViewModels, sculpted specifically for use by the view.

Any business rules should also be part of your domain, and you can implement them using domain services / factory pattern / whatever is appropriate in your domain layer, not in the MVC presentation layer. Controllers should be dumb, though not quite as dumb as models, and should give responsibility to the domain for anything that requires business knowledge. Controllers manage the flow of HTTP requests and responses, but anything with real business value should be above the controller's pay grade.

So, you can still have a layered architecture, with MVC as the presentation layer. It is a client of your application layer, service layer, or domain layer, depending on how you architect it. But ultimately your entity model should be part of the domain, not models in MVC.

Title: Javascript modularity, server based MVC & business reality

Body:
I understand this is a very broad question, but I have worked with various aspects of this problem individually and am struggling to bring all the concepts and technologies together.

I'd like to specify that answers should include these technologies:

C#

MVC 3 w/ Razor

Javascript w/jQuery

Anything above and beyond those (such as Backbone.js, Entity Framework, etc) are welcome as suggestions if they help answer the question which is:

Using the above listed technologies, what is an optimal strategy for organizing code and logic while maintaining scalability and the ability to create a rich, fast, clean UI?

Ideally the focus should be put on a solution being deployed in a business/corporate environment.  On that note, the technologies list above will not be changed so please don't offer solutions with "you should be using xxx instead of yyy that you are using now".

Background

I work with jQuery everyday, have adopted ASP.NET's MVC and have been working with C# for a long time.  So you can present solutions assuming intermediate-to-advanced knowledge of those technologies.

I'll organize the question into smaller parts to make it simpler to respond to:

1. Project structure

Given I am working with ASP.NET MVC (in Visual Studio 2010) I would like a directory structure solution that offers some acceptance of the main layout this type of application.  Something like Brunch I suppose, but with a little more detail of what each folder would contain and how it works with other areas of the app.

2. Data access

I'd like to modularize my data access as much as I can, with an API-type structure.  You can assume lots of POCO objects (User, UserGroup, Customer, OrderHeader, OrderDetails, etc), but there will also be some complex reports that require data intensive SQL and careful UI rendering.  EF + LINQ are fantastic for the former but not so much for the latter.  I can't find something that seems to fit both scenarios without being overly complicated or overly simple.

3. Client-Side Code Organization and UI Rendering

Like most developers first picking up jQuery, I fell into the trap of mashing together code wherever it needed to go but quickly found it piling up and turning ugly.  Although I've come leaps and bounds since then, I still struggle with modularizing my code and working with various parts of the UI without repeating code.

As an example, a typical piece of code I might write would look like this, I have commented the stuff that bothers me (note that I've since changed to using deferred AJAX calls and separated the actual data requests from the DOM manipulation):

```<code>$('#doSomethingDangerous').click(function () {
    // maybe confirm something first
    if (confirm('Are you sure you want to do this?')) {

        // show a spinner?  something global would be preferred so I don't have to repeat this on every page
        $('#loading').show();

        // maybe the page should notify the user of what's going on in addition to the dialog?
        $('#results').show().html('<h2>Please wait, this may take a while...</h2>');

        $.ajax({
            url: 'blah/DoDangerousThing',
            success: function (data) {
                // The results will be loaded to the DOM obviously, is there a better way to pull this type of specific code out of the data access calls?
                $('#results').empty();
                $('#results').append('<b>' + data.length + '</b> users were affected by this dangerous activity');
                $('#results').append('<ul>');

                // I've recently started to use jQuery templates for this sort of logic, is that the way to go?
                $(data).each(function (i, user) {
                    $('#results').append('<li>' + user.Username + '</li>');
                });
                $('#results').append('</ul>');

                // Need to hide the spinner, again would prefer to have this done elsewhere
                $('#loading').hide();
            }
        });
    }
});
</code>```

General Questions

Client MVC vs. server MVC?  My project is already a server-side MVC structure, so is there still a need for client MVC like Backbone.js provides?

Should Javascript files get created for each object (like an OrderHeader.js) and then minified/merged during the build?  Or should there just be an Order.js which has logic for OrderHeader, OrderDetails, Reports etc?

How should complex queries be handled?  Right now my leading theory is /Reports/Orders-By-Date/ or something along those lines and I use a custom SQL query that renders a custom dataset (or ViewModel) to the Razor View.  But what about paging, sorting, etc?  Is this better to be done client or server side?  (assume larger dataset - 2 to 3 second SQL query)

I've read through Microsoft's Project Silk.  Is this a good way to go?  How does it compare to Backbone.js or others?

I'm very accustomed to an N-tiered architecture, do these concepts somewhat throw that out the window?  It seems MVC is like a bunch of mini N-tiered sections within what would have been the front-end or top tier in the past.

Again the more specific your answers are the better they will be.  I've read a lot of high level documentation and examples, I'm trying to better understand translating it into real world examples.

Body:
TerryR my friend, you and I should have a drink. We have some similar problems.

1. Project Structure: I agree with Eduardo that the folder structure in an MVC app leaves something to be desired. You have your standard Controllers, Models, and Views folders. But then the Views folder gets broken down into a different folder for each Controller, plus a Shared folder. And each Views/ControllerName or Views/Shared can be broken down into EditorTemplates and DisplayTemplates. But it lets you decide how to organize your Models folder (you can do with or without subfolders & additional namespace declarations).

God forbid you are using Areas, which duplicate the Controllers, Models, and Views folder structure for each area.

/Areas
    /Area1Name
        /Controllers
            FirstController.cs
            SecondController.cs
            ThirdController.cs
        /Models
            (can organize all in here or in separate folders / namespaces)
        /Views
            /First
                /DisplayTemplates
                    WidgetAbc.cshtml <-- to be used by views in Views/First
                /EditorTemplates
                    WidgetAbc.cshtml <-- to be used by views in Views/First
                PartialViewAbc.cshtml <-- to be used by FirstController
            /Second
                PartialViewDef.cshtml <-- to be used by SecondController
            /Third
                PartialViewMno.cshtml <-- to be used by ThirdController
            /Shared
                /DisplayTemplates
                    WidgetXyz.cshtml <-- to be used by any view in Area1
                /EditorTemplates
                    WidgetXyz.cshtml <-- to be used by any view in Area1
                PartialViewXyz.cshtml <-- to be used anywhere in Area1
            _ViewStart.cshtml <-- area needs its own _ViewStart.cshtml
            Web.config <-- put custom HTML Helper namespaces in here
        Area1NameRegistration.cs <-- define routes for area1 here
    /Area2Name
        /Controllers
        /Models
        /Views
        Area2NameRegistration.cs <-- define routes for area2 here

/Controllers
    AccountController.cs
    HomeController.cs
/Models
/Views
    /Account
        /DisplayTemplates
            WidgetGhi.cshtml <-- to be used views in Views/Account
        /EditorTemplates
            WidgetGhi.cshtml <-- to be used views in Views/Account
        PartialViewGhi.cshtml <-- to be used by AccountController
    /Home
        (same pattern as Account, views & templates are controller-specific)
    /Shared
        /DisplayTemplates
            EmailAddress.cshtml <-- to be used by any view in any area
            Time.cshtml <-- to be used by any view in any area
            Url.cshtml <-- to be used by any view in any area
        /EditorTemplates
            EmailAddress.cshtml <-- to be used by any view in any area
            Time.cshtml <-- to be used by any view in any area
            Url.cshtml <-- to be used by any view in any area
        _Layout.cshtml <-- master layout page with sections
        Error.cshtml <-- custom page to show if unhandled exception occurs
    _ViewStart.cshtml <-- won't be used automatically in an area
    Web.config <-- put custom HTML Helper namespaces in here

This means if you are working with something like a WidgetController, you have to look in other folders to find the related WidgetViewModels, WidgetViews, WidgetEditorTemplates, WidgetDisplayTemplates, etc. As cumbersome as this may be, I stick to it and don't deviate from these MVC conventions. As far as putting a model, controller, and view in the same folder but with different namespaces, I avoid this because I use ReSharper. It will squiggly underline a namespace that doesn't match the folder where the class is located. I know I could turn this R# feature off, but it helps in other parts of the project.

For non-class files, MVC gives you Content and Scripts out of the box. We try to keep all of our static / non-compiled files in these places, again, to follow convention. Any time we incorporate a js library that uses themes (images and or css), the theme files all go somewhere under /content. For script, we just put all of them directly into /scripts. Originally this was to get JS intellisense from VS, but now that we get JS intellisense from R# regardless of placement in /scripts, I suppose we could deviate from that and divide scripts by folder to better organize. Are you using ReSharper? It is pure gold IMO.

Another little piece of gold that helps a lot with refactoring is T4MVC. Using this, we don't need to type in string paths for area names, controller names, action names, even files in content & scripts. T4MVC strongly types all of the magic strings for you. Here's a small sample of how your project structure doesn't matter as much if you're using T4MVC:

// no more magic strings in route definitions
context.MapRoutes(null,
    new[] { string.Empty, "features", "features/{version}" },
    new
    {
        area = MVC.PreviewArea.Name,
        controller = MVC.PreviewArea.Features.Name,
        action = MVC.PreviewArea.Features.ActionNames.ForPreview,
        version = "december-2011-preview-1",
    },
    new { httpMethod = new HttpMethodConstraint("GET") }
);

@* T4MVC renders .min.js script versions when project is targeted for release *@
<link href="@Url.Content(Links.content.Site_css)?r=201112B" rel="stylesheet" />
<script src="@Url.Content(Links.scripts.jquery_1_7_1_js)" type="text/javascript">
</script>

@* render a route URL as if you were calling an action method directly *@
<a href="@Url.Action(MVC.MyAreaName.MyControllerName.MyActionName
    (Model.SomeId))">@Html.DisplayFor(m => m.SomeText)</a>

// call action redirects as if you were executing an action method
return RedirectToAction(MVC.Area.MyController.DoSomething(obj1.Prop, null));

2. Data access: I have no experience with PetaPoco, but I'm sure it's worth checking out. For your complex reports, have you considered SQL Server Reporting services? Or, are you running on a different db? Sorry I'm not clear on what exactly you are asking for. We use EF + LINQ, but we also put certain knowledge about how to generate reports in domain classes. Thus, we have controller call domain service call repository, instead of having controller call repository directly. For ad-hoc reports we use SQL Reporting Services, which again isn't perfect, but our users like to be able to bring data into Excel easily, and SSRS makes that easy on us.

3.  Client-Side Code Organization and UI Rendering: This is where I think I may be able to offer some help. Take a page from the book of MVC unobtrusive validation and unobtrusive AJAX. Consider this:

<img id="loading_spinner" src="/path/to/img" style="display:none;" />
<h2 id="loading_results" style="display:none;">
    Please wait, this may take a while...
</h2>
<div id="results">
</div>
<input id="doSomethingDangerous" class="u-std-ajax"
    type="button" value="I'm feeling lucky"
    data-myapp-confirm="Are you sure you want to do this?"
    data-myapp-show="loading_spinner,loading_results"
    data-myapp-href="blah/DoDangerousThing" />

Ignore the ajax success function for now (more on this later). You can get away with a single script for some of your actions:

$('.u-std-ajax').click(function () {
    // maybe confirm something first
    var clicked = this;
    var confirmMessage = $(clicked).data('myapp-confirm');
    if (confirmMessage && !confirm(confirmMessage )) { return; }

    // show a spinner?  something global would be preferred so
    // I dont have to repeat this on every page
    // maybe the page should notify the user of what's going on
    // in addition to the dialog?
    var show = $(clicked).data('myapp-show');
    if (show) {
        var i, showIds = show.split(',');
        for (i = 0; i < showIds.length; i++) {
            $('#' + showIds[i]).show();
        }
    }

    var url = $(clicked).data('myapp-href');
    if (url) {
        $.ajax({
            url: url,
            complete: function () {
                // Need to hide the spinner, again would prefer to
                // have this done elsewhere
                if (show) {
                    for (i = 0; i < showIds.length; i++) {
                        $('#' + showIds[i]).hide();
                    }
                }
            }
        });
    }
});

The above code will take care of the confirmation, showing the spinner, showing the wait message, and hiding the spinner / wait message after the ajax call is complete. You configure the behaviors using data-* attributes, like the unobtrusive libraries.

General Questions

- Client MVC vs. server MVC? I didn't try to librarify the actions you took in the success function because it looks like your controller is returning JSON. If your controllers are returning JSON, you might want to look at KnockoutJS. Knockout JS version 2.0 was released today. It can plug right into your JSON, so that an observable click can automatically bind data to your javascript templates. On the other hand if you don't mind having your ajax action methods return HTML instead of JSON, they can return the already-constructed UL with its LI children, and you can append that to an element by using data-myapp-response="results". Your success function would then just look like this:

success: function(html) {
    var responseId = $(clicked).data('myapp-response');
    if (responseId) {
        $('#' + responseId).empty().html(html);
    }
}

To sum up my best answer for this, if you must return JSON from your action methods, you are skipping the server-side View, so this really isn't server MVC -- it's just MC. If you return PartialViewResult with html to ajax calls, this is server MVC. So if your app must return JSON data for ajax calls, use client MVVM like KnockoutJS.

Either way, I don't like the JS you posted because it mixes your layout (html tags) with behavior (asynchronous data load). Choosing either server MVC with partial html views or client MVVM with pure JSON viewmodel data will solve this problem for you, but manually constructing DOM/HTML in javascript violates separation of concerns.

- Javascript file creation Apparently minification features are coming in .NET 4.5. If you go the unobtrusive route, there shouldn't be anything stopping you from loading all of your JS in 1 script file. I would be careful about creating different JS files for each entity type, you will end up with JS file explosion. Remember, once your script file is loaded, the browser should cache it for future requests.

- Complex queries I don't consider having feature like pagination, sorting, etc, as being complex. My preference is to handle this with URL's and server-side logic, to make the db queries as limited as needed. However we are deployed to Azure, so query optimization is important to us. For example: /widgets/show-{pageSize}-per-page/page-{pageNumber}/sort-by-{sortColumn}-{sortDirection}/{keyword}. EF and LINQ to Entities can handle pagination and sorting with methods like .Take(), .Skip(), .OrderBy(), and .OrderByDescending(), so you get what you need during the db trip. I haven't found the need for a clientlib yet, so I honestly don't know much about them. Look to other answers for more advice on that.

- Project silk Never heard of this one, will have to check it out. I am a big fan of Steve Sanderson, his books, his BeginCollectionItem HtmlHelper, and his blog. That said, I don't have any experience with KnockoutJS in production. I have checked out its tutorials, but I try not to commit to something until it's at least version 2.0. Like I mentioned, KnockoutJS 2.0 was just released.

- N-tier If by tier you mean different physical machine, then no, I don't think anything goes out any windows. Generally 3-tier means you have 3 machines. So you might have a fat client as your presentation tier, that runs on a user's machine. The fat client might access a service tier, that runs on an application server and returns XML or whatever to the fat client. And the service tier might get its data from a SQL server on a 3rd machine.

MVC is one layer, on 1 tier. Your controllers, models, and views are all part of your Presentation Layer, which is 1 tier in the physical architecture. MVC implements the Model-View-Controller pattern, which is where you might be seeing additional layers. However, try not to think of these 3 aspects as tiers or layers. Try to think of all 3 of them as Presentation Layer Concerns.

Update after pres/bus/data comment

Okay, so you are using tier and layer interchangably. I usually use the term "layer" for logical / project / assembly divisions, and tier for physical network separation. Sorry for the confusion.

You will find quite a few people in the MVC camp who say you should not use the "Models" in MVC for your entity data model, nor should you use your Controllers for business logic. Ideally your models should be view-specific ViewModels. Using something like Automapper, you take your entities from your domain model and DTO them into ViewModels, sculpted specifically for use by the view.

Any business rules should also be part of your domain, and you can implement them using domain services / factory pattern / whatever is appropriate in your domain layer, not in the MVC presentation layer. Controllers should be dumb, though not quite as dumb as models, and should give responsibility to the domain for anything that requires business knowledge. Controllers manage the flow of HTTP requests and responses, but anything with real business value should be above the controller's pay grade.

So, you can still have a layered architecture, with MVC as the presentation layer. It is a client of your application layer, service layer, or domain layer, depending on how you architect it. But ultimately your entity model should be part of the domain, not models in MVC.

OwnerDisplayName: olivehour


答:
1. Project structure

I have 2 project files in my solution

1) Service/Business layer I place all my Business logic and DB access code and POCOs into this separate project. No need for a Data Access layer if you using a ORM as the ORM already abstracts the DB layer.

2) UI layer contains all my Views, Controllers, Models, Scripts, CSS

I try to make my controllers, Views, scripts and CSS all use a similar folder structure. Also structure my files to match the URL path as much as possible. To avoid having to write custom routing.

Use the DisplayTemplates, EditorTemplates, Partial views and the Shared folder as much as possible.

I then structure all my Scripts to match the same Areas, Controllers of my c# files
So I would have a common.js file at the root  a js file per page and a common.js file for each area.

CSS files I normally have 2 + n  (where n is the number of areas)
1st CSS file is CSS just for the landing page only to help with a quicker page load time (probably not so important for business/corporate environment)
2nd CSS file is a common.css which has all the styles for all the other pages.
Then another common.css file for each area for example a AdminArea.css file which has CSS for every admin page.

2. Data access

If I use Entity Framework I use CodeFirst as it works very well with POCOS and you do not have a model to maintain. nHibernate is much more powerful but has a steper learning curve.
For Paging of DB results I have a reuseable util c# class and patial view I use for all my views.

For complex queries and generating reports I use Stored procedures. They are much easier to write and maintain and offer more power the LINQ.
They can also be reused by other services like SSRS. I use automapper to convert the dataset returned to back to the same POCOs entiry framework uses.

3. Client-Side Code Organization and UI Rendering

Eduardo Molteni answer has a good example code.  Additionally I would definitely recommend using knockoutjs as it has both good templating and bindings.
If you use JSON for all your AJAX calls which I use a lot of then having the UI auto map to the JS objects is a huge time saver.

General Questions

Complex queries should live in a stored proc. (see  emeraldcode.com comment)

You still keep your N-tiered architecture using this MVC.

OwnerDisplayName: Daveo


答:
I've recently been moved to believe that, if you plan on using the three technologies you listed, you should first start by assuming the adoption of Orchard CMS.  I believe it is the best single answer to your central requirement:

What is an optimal strategy for organizing code and logic while
  maintaining scalability and the ability to create a rich, fast, clean
  UI?

In the Ochard scenario, anything you can't address through its configuration mechanisms you would then handle either through the addition of free online modules, or writing your own module (which of course are C#, razor, etcetera).  Code organization is a strength of Orchard.

As for data access, there are enough pros and cons to a full-bore ORM that I've also come to think that a micro-ORM is the best take.  Try Massive or Dapper.  Both were featured on Hanselminutes.  I'll summarize the two by saying this: abstractions from SQL almost invariably break down as a project scales up.  In the end, the best solution for DB access is this abstraction called SQL (bit of sarcasm, but true).  Let the micro-ORM work with that, and you've got gold.

Put Orchard together with the micro-ORMs, and you can slice steel like butter.  Er, meaning you can develop quickly, scale, and have code that is readily maintainable by a team that receives the hand-off.

OwnerDisplayName: Brent Arias


问:
Should I learn a programming language before I attend college for Computer Engineering?
I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>

答: It depends on the college. When I studied what they call "Computer Science" at California State University, they (rightfully, in my opinion) concentrated on the science aspect of it, and they expected everyone (even freshmen) to already know how to use operating systems and how to write code in some popular language. They did not accept to transfer some credits I had gained while attending language courses at a State University of Ohio. (That was a bummer for me, but again, I understand it.)  This also had an upside: I completed an assignment once, writing my code in C; the professor could not read C, so he asked me to rewrite it in Pascal. I asked the head of the department about the rightfulness of this request, and he said that since they do not teach languages, they also cannot expect anyone to complete an assignment on any specific language. So my professor had to live with my assignment written in C. So, the bottom line is, check with the university you are going to go to. But if you want my advice, it never hurts to learn as much as possible beforehand.</p>


答: I'm going to say that I don't think it will matter too much which language you know when you start, but it will probably give you an advantage in the sense that when you get your first programming assignment, you don't have to struggle with the problem of thinking in terms of code - you will already have some experience there. One less learning curve to overcome is a good thing. Bonus if you learn the language they teach in your first year, but not necessary.</p>

Title: Should I learn a programming language before I attend college for Computer Engineering?

Body: I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>