答:
I haven't considered this in a while for most sites I've worked on given the user base I typically have. Largely, it's a matter of knowing your user base and what they have enabled. You can use various analytics scripts to determine this.

Along the same lines, I am more careful now about providing a good experience on mobile devices when it comes to using Javascript widgets. For example, I avoid using a lot of resizing tricks since they cause problems with pinch-zoom and orientation flip functionality and dropdown menus since they're difficult to use on a mobile touch screen.


问:
Advantages and disadvantages to making common unit test scaffolding code
For the project my team and me are working on we often find that we need large pieces of scaffolding code. Creating domain objects with correct values, setting up mocks for repositories, dealing with the cache,... are all things that occur commonly throughout the tests. A lof of times we're working with the same basic objects that are central to our domain (person,...) so lots of tests create instances of these objects for other objects to work on. We have a lot of different solutions using the base domain so this kind of code is often spread across those solutions.

I've been thinking about creating common classes that do a lot of this scaffolding. This would allow us to request a fully instantiated person with everything set up (access via repository, caching...). This removes duplicate code from our individual unit tests but would also mean there is a large amount of code that probably does 'too much' per test (as it would set up a full object and not just the parts required).

Has anyone ever done this? Are there any insights, remarks, thoughts... you can offer that might validate or invalidate this approach?

答:
All the possibilities summed up in the answers:

Use the Builder pattern (Bedwyr Humphreys, DXM and Pascal Mestdach)

Advantages:

No code duplication in tests

Can combine different builders for complex tests

Clean interface

Big object graphs from builders can influence test outcome

Disadvantages:

Builders must be written and maintained

Builder code must be tested as well

Builder code will need constant grooming and attention

Use a test database (Tony Hopkinson and Sam)

Advantages:

Simplicity

All data in one central place

Can use data-acces code already developed

Usable for domain objects that are not POCO (eg. Active Record,...)

Disadvantages:

Requires the use of the DAL wich might interfere with tests

Not 'pure' TDD

'Black box', need to take a look at the database to see what data your objects contain

Create domain objects per test (Peter)

Advantages:

Isolated test code

No 'black box', what you see in the test code is what you get

Disadvantages:

Code duplication for common objects

Use Facades for domain objects (Raedwald)

Advantages:

Simple tests

Disadvantages:

Not usable in all cases

Code hidden behind Facade needs testing as well

OwnerDisplayName: JDT

ContentLicense: CC BY-SA 3.0


问:
Best practices for moving large MS Access application towards .Net?
We have a really huge MS Access application developed in-house initially for our personal needs which then was turned into a commercial software and successfully sold. The software is a sort of "all-round-software-for-your-business" and contains several modules including Document Management System, Enterprise Resource Planning, Inventory Management, Customer Relationship Management, Data Analysis etc. We are quite satisfied with the current functionality of the application, but in order to meet the requests from our clients we realize that we have to move to something new.

We decided to gradually move our application towards .Net because we can stick to Visual Basic .Net: even though it is a new language for most of the developers here, we have deep knowledge of VBA and several dozen small projects implemented in VB6.

We already started moving the data layer functionality of our application to MS SQL Server, so that every data manipulation and search is performed directly on the server.

What we are looking for are best practices for gradually moving our extensive GUI (about 500-600 different forms including subforms, about 200 reports with multi-language support etc). Following the recent request from our potential customer to implement asynchronous data encryption on documents in DMS we would be also happy to completely decouple this part from MS Access and implement it in .Net.

The question is how to seamlessly integrate the .Net application with the existing MS Access system, so that we can invoke it with certain parameters (user rights etc.) and enable data exchange between this application and running MS Access application.

EDIT:

We tried to apply some practices from Martin Fowler's book "Enterprise intergration patterns" to achieve some integration between the MS Access application and some small utilities we implemented in .Net for various needs. But we only managed to use the "shared database" pattern and weren't really satisfied with our solution.

For instance, we implemented a small utility running as a Windows service which automatically downloads all messages from the mail server using POP3 connection and stores them into one table, whereas all attachments are stored in file system.

What we mainly did is we used ADO.NET to directly access MS Access databases in MDB format and populate table with some processed data (like the data about mail messages from the example above: we have fields for FROM, TO, CC, BCC, Subject and Body).

There is absolutely no problem to work with MDB data format from .Net, moreover we don't want to stay with MDB and upsized almost everything to MS SQL Server 2008 -- this gives us much more freedom concerning the data management and scalability.

The main problem here is that we don't know how to implement a sort of "callback" in Access so that we can trigger the execution of certain VBA code on data update.

We had great hopes with MS Access 2010 supporting update and insert triggers for data tables, but it turned out that we can only use MS Access Macros for these triggers and there is no way to execute any custom VBA code within the trigger.

We also tried some solutions with sending keystrokes directly to MS Access window to mimick some user-invoked data requery. This works, but we don't think this is a realiable solution that can be used in production.

We also looked into DDE for MS Access, but we couldn't find any good sample solution implementing DDE commands and using them for in-memory data and command exchange.

So, the main problem is to have MS Access and .Net application co-exist and interact with each other.

EDIT2:

I forgot to mention what we also implemented MSMQ library in VBA for message passing between .Net and MS Access, the problem was again the lack of callback here: we really had to poll the queue for new messages and given that VBA does not really support multi-threading it wasn't really a nice solution.

答:
Here is a kind of plan to turn your MS Access application into a VB.Net application by mutation.

This is not a general plan, the following plan depends of the project you've described.

Step 1: migrate all data to SQL Server

Do not use ODBC for connection Access to SQL Server, use an Access Project (ADP) instead. An Access Project is an Access file with an .adp extension, it has full Access features (Macros, Forms, Reports, Modules) but the connection is directly on an SQL Server database instead of an MDB file. ADP files are very compatible with MDB files. They seem to not be supported in Access 2010, while in fact the feature is hidden but it is very well supported. Like MDE, ADP files can be "compiled" into ADE files.

Migrating into SQL Server will cost few modifications in data structure and code, but all is quite easy to migrate. And it is a final target after all.

Forget about triggering database events to VBA or VB.Net code. This can technically be done using SQL Server Extended Stored Procedures, but is is a very bad trick. Your project has a future life, so it is better to enforce its Data structure by avoiding such kind of destructuring bridge. In general, play down with database triggers, it's smart but quite difficult to maintain.

Step 2: make authentication uniform

It's a good thing that your application is not bases on Access security (MDW file).

Make a plan for the target authentication for the VB.Net application, and then define a way to migrate the Access authentication to this target in order to have a uniform authentication between the two applications.

Since authentication is transverse in an application architecture, this will be more easy to slice between the Access version to the VB.Net version.

Step 3: prepare a token feature in order to make a bridge between Access and VB.Net

You said, the Access UI will have to open a VB.Net UI with some accurate parameters and also authentication. And you'll probably have to do the same in the other way.

A good solution is to build a small token feature based on a token table : columns can be a token id (integer), a token key (long string), a token date, and a parameter list (long string or text). Each time Access needs to open a VB.Net screen, then save a token in the database with the parameters, and then open your VB.Net application with only the token id and the token key. The VB.Net opens, search the token id in the database, checks the key (this applies as an authentication) and read the parameters. Then it open to corresponding form, and do what is required. Don't forget to give a duration to tokens, and to clean old tokens.

If you need to callback from VB.Net to Access (you probably will), then I think it is possible to activate some VBA code on an opened MDB Access file, using OLE.

Step 4: migrate UI and Modules screen by screen, module by module

Now the big of the preparation is done. You can start to migrate user interface from Ms Access to VB.Net.

There is no good automatic tools for doing this. VBA and .Net are too different. You have to prepare your work for such a migration. Start with a small form, like the "About" box, and continue from simple forms to complicated forms. Of course you will have to bundle and schedule some migrations, but you will gradually migrate your screens, reports and libraries from Ms Access to VB.Net.


问:
Is there any license restriction to avoid binary translation of CIL to custom bytecode?
Prior to actual question, let me summarize what I'm trying to do. I plan to implement a small, JIT-enabled, register-based VM runtime. Instead of making a proper compiler (which is hard IMO) for a super-fancy home-brew language, I decided to implement a binary translator from a appropriate bytecode (much like Dalvik VM approach). Considering CIL vs. Java bytecode, CIL is best for my needs.

As a note, I wanted to list some important things to avoid possible confusions:

Base Core Library (BCL) or any Microsoft specific assemblies won't be decompiled and translated. Instead, BCL references will be subject to substitution with my VM specific codes at translation phase (much like COSMOS Plugs approach).

All CIL opcodes won't be translated. So, directly using CIL is not an option.

"Any" .NET executable is not targetted for translation. .NET will be a tool, not target.

Dalvik VM is good example what I'm trying to do. In Dalvik case, programs are written in Java, but Java byte codes translated into Dalvik opcodes. In my case, programs will be written in .NET, but CIL will be translated into "fancy" VM opcodes.

Custom VM itself will be closed source and it will be in a free software initially. But, in time, it might be used in open source and/or commercial projects.

So, is there any license restriction to avoid me doing this? If so, how can I avoid the restrictions? Making only non-profit applications or making it open source?

EDIT: I won't use CLI, CLR or any other thing which is distributed from Microsoft. I won't redistribute or integrate SSCLI into my applications either. The question is about translating CIL code into custom byte codes which will be done with my own tools. So, it's actually decompilation of my own custom .NET executables into a different byte codes to serve my needs in production phase. So, essentially I'll use .NET compilers as a front-end for my decompiler, but I won't redistribute .NET compilers either.

EDIT2: CLI AND CIL ARE DIFFERENT THINGS!

答:
If i had understood your question correctly i think all you are saying is that you will create your own system (compiler or Virtual machine) which takes CIL byte codes and do something interesting. This do something can be of course translating into executable or another IL which is later interpreted.

Now the question really is - the CIL being a Microsoft intellectual property will they sue you?

The wiki link of Mono provides some interesting links on this; Accordingly,

When Microsoft first announced their .NET Framework in June 2000 it
  was described as "a new platform based on Internet standards", and
  in December of that year the underlying Common Language Infrastructure
  was published as an open standard, "ECMA-335" - opening up the
  potential for independent implementations.

Here is the home for this reference. The Microsoft's development center's page gives good details. According to this CIL instruction set is part (part III) of the specs in overall CLI standard. The site also mentions that there are following companies involved in developing this standard.

Many of the organizations that have participated in the TC39/TG2 and
  TC39/TG3 work have volunteered to mirror this site. The links for the
  mirror sites are:

Intel Corporation,

  ISE (Eiffel),

  IT University, Copenhagen

  Kahu Research, New Zealand

  Microsoft Corporation

  Novell (Mono)

According to same wiki reference:

On July 6, 2009, Microsoft announced that it was placing their ECMA
  334 and ECMA 335 specifications under their Community Promise pledging
  that they would not assert their patents against anyone implementing,
  distributing, or using alternative implementations of .NET

Now based on all above research, we can say that - given that the ECMA is an open standard, you can actually do legally what you propose to do.

NOTE: there are some component not included in this spec. Also, using .NET CLR itself is not part this discussion.

DISCLAIMER: But yes, great many details go in legality. So since i am not lawyer, my advise to you is for free but without any warranty! :)

OwnerDisplayName: Osman Turan


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

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

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

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

Then in the C# code I collect the list:

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

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

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

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

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

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

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

答:
To set a input tag that doesn't need serverside asp, you can use: (or <%# %> for forms databinding)

html:

```<code><input type="hidden" value='<%= RandomValues %>' name="RANDOM_VALUES" />
</code>```

asp control:

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

to get the values on postback

```<code>Request.Form["RANDOM_VALUES"]
</code>```

If its, asp control hidden input, you can use

```<code>Request.Form[RandomList.UniqueID]
</code>```

The neat part about Request.Form is if you have multiple tags with the same "name" attribute, it will return the result in CSV.

Body:
To set a input tag that doesn't need serverside asp, you can use: (or <%# %> for forms databinding)

html:

<input type="hidden" value='<%= RandomValues %>' name="RANDOM_VALUES" />

asp control:

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

to get the values on postback

Request.Form["RANDOM_VALUES"]

If its, asp control hidden input, you can use

Request.Form[RandomList.UniqueID]

The neat part about Request.Form is if you have multiple tags with the same "name" attribute, it will return the result in CSV.


答:
JSON is the best practice way to accomplish the task.  Do not look at the problem as a passing between "C# and JavaScript".  This way of thinking leads to code oddities such as what you have in the original post.

More generally, it's just passing objects between the client and the server in a language agnostic fashion.  JSON is great for the task because it's widely supported and easy to read.

Title: How should data be passed between client-side Javascript and C# code behind an ASP.NET app?

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

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

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

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

Then in the C# code I collect the list:

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

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

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

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

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

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

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


问:
What's the best place for a high school programmer to get his work noticed?
I'm a 16 year old high school student, with a passion for computer programming.
I'm in grade 11, and I've been learning it as part of the school syllabus for about 8 months.
I've gone beyond what's being taught at school, and witten a few (reasonably good) applications. The language that I program in is C++, on the windows platform.
Eventually I'd like to major in CS at a good college and then work as a programmer.

The specific questions that I have are:

What is a good place for me to get my work noticed ?

Are there any journals, or publications specifically for young programmers ?

If not publications, then are there any good blogs, or is it just better to start your own ?

Is there anything else, that would help me get noticed as a programmer ?

I've tried to be as objective as possible.

If all this was tl;dr:
What's the best way to get noticed as a young programmer ?

Edit:
I am not looking to get hired straight out of high school
The aim is not to impress the community as a professional programmer.
This is with intent towards college applications where having your work seen and critiqued by other people will improve your application. I am not looking to earn money from what I've written (so far).

答:
I think that JohnFX gave a great answer to this question.

A few thoughts:

I think jQueryUI might be the best place to start.  It is fun and visual. So you can go on the jQueryUI developer forum on the jQuery site and ask to be a contributor.

I think you will be demonstrating great passion and dedication for programming more than you will be demonstrating great skill. But don't let that stop you!  I strongly encourage you to be involved.

At this point you might have to settle for doing QA.  QA is boring but you can accept it and show dedication.  But from there you can contribute a bit of code and maybe make plugins.

If you ask to be involved in something and they make it difficult, it is because they are assholes.  Just look for a project where the people are encouraging and nice.

After you find a project with encouraging, nice people and you contribute, you can ask one of the adult contributors or hopefully one of the people in charge of the project to write you a short letter of recommendation.


问:
Graduate expectations versus reality
When choosing what we want to study, and do with our careers and lives, we all have some expectations of what it is going to be like. Now that I've been in the industry for almost a decade, I've been reflecting a bit on what I thought (back when I was studying Computer Science) programming working life was going to be like, and how it's actually turning out to be.

My two biggest shocks (or should I say, broken expectations) by far are the sheer amount of maintenance work involved in software, and the overall lack of professionalism:

Maintenance: At uni, we were all told that the majority of software work is maintenance of existing systems. So I knew to expect this in the abstract. But I never imagined exactly how overwhelming this would turn out to be. Perhaps it's something I mentally glazed over, and hoped I'd be building cool new stuff from scratch a lot more. But it really is the case that most jobs are overwhelmingly maintenance, bug fixing, and support oriented.

Lack of professionalism: At uni, I always had the impression that commercial software work is very process-oriented and stringently engineered. I had images of ISO processes, reams of technical documentation, every feature and bug being strictly documented, and a generally professional environment. It came as a huge shock to realise that most software companies operate no differently to a team of students working on a large semester-long project. And I've worked in both the small agile hack shop, and the medium sized corporate enterprise. While I wouldn't say that it's always been outright "unprofessional", it definitely feels like the software industry (on the whole) is far from the strong engineering discipline that I expected it to be.

Has anyone else had similar experiences to this? What are the ways in which your expectations of what our profession would be like were different to the reality?

答:
I thought after graduating that the people in charge would be able to recognize good work from bad work.  After being handed the millionth copy of "really great code our top coder put together" and having it look like this:

```<code>def lf(p, q, r):
    x = 4
    xx = 4.5
    t = {1:p, 2:p+2, 3:p*4} #I think there's a bug in here but I don't know
    .
    .
    .
</code>```

I've almost given up trying to understand what goes on between the ears of the pointy-haired boss.  "Great" means maintainence nightmare, "good" means crashes in a gentle breeze, and "horrible mess" means either that or a well structured code base whose engineers have patently refused to meet obscene deadlines just to keep their sanity.

Title: Graduate expectations versus reality

Body:
I thought after graduating that the people in charge would be able to recognize good work from bad work.  After being handed the millionth copy of "really great code our top coder put together" and having it look like this:

def lf(p, q, r):
    x = 4
    xx = 4.5
    t = {1:p, 2:p+2, 3:p*4} #I think there's a bug in here but I don't know
    .
    .
    .

I've almost given up trying to understand what goes on between the ears of the pointy-haired boss.  "Great" means maintainence nightmare, "good" means crashes in a gentle breeze, and "horrible mess" means either that or a well structured code base whose engineers have patently refused to meet obscene deadlines just to keep their sanity.

ContentLicense: CC BY-SA 2.5


问:
How does unit testing work?
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.
For instance, the Wikipedia example:

```<code>public class TestAdder {
    public void testSum() {
        Adder adder = new AdderImpl();
        assert(adder.add(1, 1) == 2);
        assert(adder.add(1, 2) == 3);
        assert(adder.add(2, 2) == 4);
        assert(adder.add(0, 0) == 0);
        assert(adder.add(-1, -2) == -3);
        assert(adder.add(-1, 1) == 0);
        assert(adder.add(1234, 988) == 2222);
    }
}
</code>```

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

```<code>assert(adder.add(a, b) == (a+b));
</code>```

but then this is just coding the function itself in the test.
Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:
I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)

答:
I feel like the only unit testing I could do would be to simply re-code the algorithm in the test

You are nearly correct for such a simple class.

Try it for a more complex calculator.. Like a bowling score calculator.

The value of unit tests is more easily seen when you have more complex "business" rules with different scenarios to test for.

I'm not saying you shouldn't test a run of the mill calculator (Does your calculator account issues in values like 1/3 that can't be represented?  What does it do with division by zero?) but you will see the value more clearly if you test something with more branches to get coverage on.

Title: How does unit testing work?


答:
Despite religous zealotry about 100% code coverage, I will say that not every method should be unit tested.  Only functionality that contains meaningful business logic.  A function that simply adds number is pointless to test.

I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this

There is your real problem right there.  If unit testing seems unnaturally hard or pointless then it is likely because of a design flaw.  If it were more object oriented your method signatures would not be so massive and there would be fewer possible inputs to test.

I don't need to go into my OO is superior to procedural programming...

Title: How does unit testing work?

Body:
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.
For instance, the Wikipedia example:

```<code>public class TestAdder {
    public void testSum() {
        Adder adder = new AdderImpl();
        assert(adder.add(1, 1) == 2);
        assert(adder.add(1, 2) == 3);
        assert(adder.add(2, 2) == 4);
        assert(adder.add(0, 0) == 0);
        assert(adder.add(-1, -2) == -3);
        assert(adder.add(-1, 1) == 0);
        assert(adder.add(1234, 988) == 2222);
    }
}
</code>```

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

```<code>assert(adder.add(a, b) == (a+b));
</code>```

but then this is just coding the function itself in the test.
Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:
I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)


问:
Structuring Visual Studio folders
If I'm doing a website, I end up with folders like "Controllers, Views, Models, Extensions, and Helpers". If I'm doing a DLL library I end up with folders reflecting the namespaces of my classes. If I write a desktop app, I end up with "Presentation and models" where models is subdivided further by namespaces.

My question is, where is a common place to put classes that aren't necessarily part of your logic or model?

For instance, if I find some code to convert XML to some arbitrary format, I usually put it in a static class and drop it in a folder called utilities. That's easy, but when I get into something that borders on domain logic that converts from XML into a domain specific language, where do I draw the line?

That's a pretty specific case, but I run into tons of these where I'm torn on putting it in the Utilities folder, the helpers folder etc. These are all folders I use, but hopefully the concept is clear, I just don't know how to organize my code when it isn't clear domain logic.

答: If I have some code that needs to be used by domain logic, but isn't actually domain logic, I'll usually create a "Utility" folder inside the folder which houses the actual domain logic. That way the code is separate, but what it should be used with is immediately obvious. This creates a new namespace at the level I plan on using the utility classes which makes it easy to see when something is a utility versus domain logic (utilities will be prefixed by a "Utility." or otherwise.</p>

Title: Structuring Visual Studio folders


答:
You are asking for a best practice on how to do the wrong thing.  There is not one.  Best practices encompass how to effectively create a maintainable system, so that even if a bus crashes and a whole new team needs to come in cold, the development and support can continue.  The system you describe is going to send most developers running for the hills.  You have product built with obsolete technology and want to interface with today's technology.  And you want to do so with out addressing any of the anti patterns you have described for the core product. Those developers that are willing to tackle it would likely be unwilling to do so with the conditions you propose. </p>

<p>However your bus has not crashed so you can leverage the existing team that understands the system.  The best way to develop gradually that I have found is using the Agile Methodology.  It supports an iterative process that addresses the high risk requirements early on and addresses business needs well.  </p>

Title: Best practices for moving large MS Access application towards .Net?

Body:
We have a really huge MS Access application developed in-house initially for our personal needs which then was turned into a commercial software and successfully sold. The software is a sort of "all-round-software-for-your-business" and contains several modules including Document Management System, Enterprise Resource Planning, Inventory Management, Customer Relationship Management, Data Analysis etc. We are quite satisfied with the current functionality of the application, but in order to meet the requests from our clients we realize that we have to move to something new.

We decided to gradually move our application towards .Net because we can stick to Visual Basic .Net: even though it is a new language for most of the developers here, we have deep knowledge of VBA and several dozen small projects implemented in VB6.

We already started moving the data layer functionality of our application to MS SQL Server, so that every data manipulation and search is performed directly on the server.

What we are looking for are best practices for gradually moving our extensive GUI (about 500-600 different forms including subforms, about 200 reports with multi-language support etc). Following the recent request from our potential customer to implement asynchronous data encryption on documents in DMS we would be also happy to completely decouple this part from MS Access and implement it in .Net.

The question is how to seamlessly integrate the .Net application with the existing MS Access system, so that we can invoke it with certain parameters (user rights etc.) and enable data exchange between this application and running MS Access application.

EDIT:

We tried to apply some practices from Martin Fowler's book "Enterprise intergration patterns" to achieve some integration between the MS Access application and some small utilities we implemented in .Net for various needs. But we only managed to use the "shared database" pattern and weren't really satisfied with our solution.

For instance, we implemented a small utility running as a Windows service which automatically downloads all messages from the mail server using POP3 connection and stores them into one table, whereas all attachments are stored in file system.

What we mainly did is we used ADO.NET to directly access MS Access databases in MDB format and populate table with some processed data (like the data about mail messages from the example above: we have fields for FROM, TO, CC, BCC, Subject and Body).

There is absolutely no problem to work with MDB data format from .Net, moreover we don't want to stay with MDB and upsized almost everything to MS SQL Server 2008 -- this gives us much more freedom concerning the data management and scalability.

The main problem here is that we don't know how to implement a sort of "callback" in Access so that we can trigger the execution of certain VBA code on data update.

We had great hopes with MS Access 2010 supporting update and insert triggers for data tables, but it turned out that we can only use MS Access Macros for these triggers and there is no way to execute any custom VBA code within the trigger.

We also tried some solutions with sending keystrokes directly to MS Access window to mimick some user-invoked data requery. This works, but we don't think this is a realiable solution that can be used in production.

We also looked into DDE for MS Access, but we couldn't find any good sample solution implementing DDE commands and using them for in-memory data and command exchange.

So, the main problem is to have MS Access and .Net application co-exist and interact with each other.

EDIT2:

I forgot to mention what we also implemented MSMQ library in VBA for message passing between .Net and MS Access, the problem was again the lack of callback here: we really had to poll the queue for new messages and given that VBA does not really support multi-threading it wasn't really a nice solution.

Body:
You are asking for a best practice on how to do the wrong thing.  There is not one.  Best practices encompass how to effectively create a maintainable system, so that even if a bus crashes and a whole new team needs to come in cold, the development and support can continue.  The system you describe is going to send most developers running for the hills.  You have product built with obsolete technology and want to interface with today's technology.  And you want to do so with out addressing any of the anti patterns you have described for the core product. Those developers that are willing to tackle it would likely be unwilling to do so with the conditions you propose.

However your bus has not crashed so you can leverage the existing team that understands the system.  The best way to develop gradually that I have found is using the Agile Methodology.  It supports an iterative process that addresses the high risk requirements early on and addresses business needs well.


问:
Benefits of rapid release development cycle adopted by the Mozilla Foundation
Which the real benefits of rapid release development cycle adopted by the Mozilla Foundation in comparison with the strategy adopted previously?</p>

答:
According to Mozilla, the rapid release schedule is to accommodate the "speed of the web", but there's no reason that same thing couldn't be accomplished releasing minor updates with minor update numbers.  They were releasing minor updates about the same pace they are now releasing "major" updates, it's just that they increment a different segment of the build number now.  So instead of going from 3.6.4 to 3.6.5 when they release some minor updates, they now go from 9.0.1 to 9.1.0 instead and anything bigger than a minor update gets a major build number increment now.  It's basically just a numbers game so 'users' don't think Firefox is somehow less good than Chrome simply because Chrome is version 16 and Firefox is version 3.6.

If you take a look at the change log for going from version 8 to 9 and look at the changes, you'll see that it should really just be a minor version update, but it's not.  The real shame is that Chrome tries (and succeeds) at hiding the version number so well that even tech people hardly pay attention to (or know) what version they are using.  With Chrome, it's always just "Chrome, version latest", which is much easier.  Then again, updates in Chrome don't require 3+ minutes to install on a Core i7.  There is some talk about moving to a "current - days" version number instead, which would be far better.  Where your version is either "current" or "current - x days" where x is the number of days ago your version was released compared to current.

OwnerDisplayName: Adriano Silva


答:
I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test

I am pretty sure that each one of your procedural functions is deterministic, so it returns a specific int result for every given set of input values. Ideally, you would have a functional specification from which you can figure out what result you should receive for certain sets of input values. In lack of that, you can run the ruby code (which is presumed to work correctly) for certain sets of input values, and record the results. Then, you need to HARD CODE the results into your test. The test is supposed to be a proof that your code does indeed produce results which are known to be correct.

Title: How does unit testing work?


答:
Rather than testing for a manually calculated return value, or duplicating the logic in the test to calculate the expected return value, test the return value for an expected property.

For example, if you want to test a method that inverts a matrix, you don't want to manually invert your input value, you should multiply the return value by the input and check that you get the identity matrix.

To apply this approach to your method, you will have to consider its purpose and semantics, to identify what properties the return value will have relative to the inputs.

Title: How does unit testing work?


答:
Unit tests are a productivity tool.  You receive a change request, implement it, then run your code through the unit test gambit.  This automated testing saves time.

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

A moot point.  The test in the example just shows how to instantiate a class and run it through a series of tests.  Concentrating on the minutia of a single implementation is missing the forest for the trees.

Can someone provide me with an example where unit testing is actually useful?

You have an Employee entity.  The entity contains a name and address.  The client decides to add a ReportsTo field.

```<code>void TestBusinessLayer()
{
   int employeeID = 1234
   Employee employee = Employee.GetEmployee(employeeID)
   BusinessLayer bl = new BusinessLayer()
   Assert.isTrue(bl.Add(employee))//assume Add returns true on pass
}
</code>```

That's a basic test of the BL for working with an employee.  The code will pass/fail the schema change you just made.  Remember that assertions are not the only thing the test does.  Running through the code also ensures no exceptions are bubbled up.

Over time, having the tests in place makes it easier to make changes in general.  The code is automatically tested for exceptions and against Assertions you make.  This avoids much of the overhead incurred by manual testing by a QA group.  While UI is still pretty difficult to automate, the other layers are generally very easy assuming you use access modifiers correctly.

I feel like the only unit testing I could do would be to simply re-code the algorithm in the test.

Even procedural logic is easily encapsulated inside a function.  Encapsulate, instantiate and pass in the int/primitive to be tested (or mock object).  Do not copy paste the code into a Unit Test.  That defeats DRY.  It also defeats the test entirely because you are not testing the code, but a copy of the code.  If the code that should have been tested changes, the test still passes!

Title: How does unit testing work?

Body:
Unit tests are a productivity tool.  You receive a change request, implement it, then run your code through the unit test gambit.  This automated testing saves time.

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

A moot point.  The test in the example just shows how to instantiate a class and run it through a series of tests.  Concentrating on the minutia of a single implementation is missing the forest for the trees.

Can someone provide me with an example where unit testing is actually useful?

You have an Employee entity.  The entity contains a name and address.  The client decides to add a ReportsTo field.

void TestBusinessLayer()
{
   int employeeID = 1234
   Employee employee = Employee.GetEmployee(employeeID)
   BusinessLayer bl = new BusinessLayer()
   Assert.isTrue(bl.Add(employee))//assume Add returns true on pass
}

That's a basic test of the BL for working with an employee.  The code will pass/fail the schema change you just made.  Remember that assertions are not the only thing the test does.  Running through the code also ensures no exceptions are bubbled up.

Over time, having the tests in place makes it easier to make changes in general.  The code is automatically tested for exceptions and against Assertions you make.  This avoids much of the overhead incurred by manual testing by a QA group.  While UI is still pretty difficult to automate, the other layers are generally very easy assuming you use access modifiers correctly.

I feel like the only unit testing I could do would be to simply re-code the algorithm in the test.

Even procedural logic is easily encapsulated inside a function.  Encapsulate, instantiate and pass in the int/primitive to be tested (or mock object).  Do not copy paste the code into a Unit Test.  That defeats DRY.  It also defeats the test entirely because you are not testing the code, but a copy of the code.  If the code that should have been tested changes, the test still passes!


答:
In my point of view unit tests are even usefull at your little adder class:
don't think of "recoding" the algorithm and think of it as a black box with the only knowledge you have about is the functional behaviour (if you are familiar with fast multiplication you know some faster, but complexer attempts than using the "a*b") and your public interface. Than you should ask yourself "What the hell could go wrong?"...

In the most cases it happens at the border (i see you test already adding these patterns ++, --, +-, 00 - time to complete these by -+, 0+, 0-, +0, -0). Think of what happens at MAX_INT and MIN_INT when adding or subtracting (adding negatives ;) ) there. Or try to make sure your tests look quite exactly what happens at and around zero.

All in all the secret is very simple (maybe for complexer ones too ;) ) for simple classes: think about the contracts of your class (see design by contract) and then test against them. The better you know your inv's, pre's and post's the "completer" your tests will be.

Hint for your test classes: try to write only one assert in a method. Give the methods good names (e.g. "testAddingToMaxInt", "testAddingTwoNegatives") to have the best feedback when your test fails after code change.

Title: How does unit testing work?


答: Anything not specific to your application should be separated into different projects (i.e. assemblies) and referenced from projects that require these assemblies. These projects will likely contain generic code that doesn't use any specific domain or business logic (e.g. sorting functions). These projects may be used by other applications at some point, so it's important that they are separate and can be referenced when needed.</p>

Title: Structuring Visual Studio folders

Body:
If I'm doing a website, I end up with folders like "Controllers, Views, Models, Extensions, and Helpers". If I'm doing a DLL library I end up with folders reflecting the namespaces of my classes. If I write a desktop app, I end up with "Presentation and models" where models is subdivided further by namespaces.

My question is, where is a common place to put classes that aren't necessarily part of your logic or model?

For instance, if I find some code to convert XML to some arbitrary format, I usually put it in a static class and drop it in a folder called utilities. That's easy, but when I get into something that borders on domain logic that converts from XML into a domain specific language, where do I draw the line?

That's a pretty specific case, but I run into tons of these where I'm torn on putting it in the Utilities folder, the helpers folder etc. These are all folders I use, but hopefully the concept is clear, I just don't know how to organize my code when it isn't clear domain logic.


答:
For a very simple function like add, testing could be considered unnecessary, but as your functions become more complex, it becomes more and more obvious why testing is necessary.

Think about what you do when you're programming (without unit testing).  Usually you write some code, run it, see that it works, and move onto the next thing, right?  As you write more code, especially in a very large system/GUI/website you find that you have to do more and more "running and seeing if it works".  You have to try this and try that.  Then, you make a few changes and you have to try those same things all over again.  It becomes very obvious that you could save time by writing unit tests that would automate the whole "running and seeing if it works" part.

As your projects become larger and larger the number of things you have to "run and see if it works" for becomes unrealistic.  So you end up just running and trying a few major components of the GUI/project and then hoping everything else is fine.  This is a recipe for disaster.  Of course you, as a human being, can't repeatedly test for every single possible situation that your clients might use if the GUI is used by literally hundreds of people.  If you had unit tests in place, you could simply run the test before shipping out the stable version, or even before committing to the central repository (if your workplace uses one).  And, if there are any bugs found later on, you can just add a unit test to check for it in the future.

Title: How does unit testing work?


答:
Unit tests, if you're testing small enough units, are always asserting the blindingly obvious.

The reason that add(x, y) even gets mention of a unit test, is because sometime later somebody will go into add and put special tax logic handling code not realizing that add is used everywhere.

Unit tests are very much about the associative principle: if A does B, and B does C, then A does C.  "A does C" is a higher-level test.  For instance, consider the following, completely legitimate business code:

```<code>public void LoginUser (string username, string password) {
    var user = db.FetchUser (username);

    if (user.Password != password)
        throw new Exception ("invalid password");

    var roles = db.FetchRoles (user);

    if (! roles.Contains ("member"))
        throw new Exception ("not a member");

    Session["user"] = user;
}
</code>```

At first glance this looks like an awesome method to unit test, because it has a very clear purpose.  However, it does about 5 different things.  Each thing has a valid and invalid case, and will make a huge permutation of unit tests.  Ideally this is broken down further:

```<code>public void LoginUser (string username, string password) {

    var user = _userRepo.FetchValidUser (username, password);

    _rolesRepo.CheckUserForRole (user, "member");

    _localStorage.StoreValue ("user", user);
}
</code>```

Now we're down to units.  One unit test does not care what _userRepo considers valid behavior for FetchValidUser, only that it's called.  You can use another test to ensure exactly what a valid user constitutes.  Similarly for CheckUserForRole ... you've decoupled your test from knowing what the Role structure looks like.  You've also decoupled your entire program from being tied strictly to Session.  I imagine all the missing pieces here would look like:

```<code>class UserRepository : IUserRepository
{
    public User FetchValidUser (string username, string password)
    {
        var user = db.FetchUser (username);

        if (user.Password != password)
            throw new Exception ("invalid password");

        return user;
    }
}

class RoleRepository : IRoleRepository
{
    public void CheckUserForRole (User user, string role)
    {
        var roles = db.FetchRoles (user);

        if (! roles.Contains (role))
            throw new Exception ("not a member");
    }
}

class SessionStorage : ILocalStorage
{
    public void StoreValue (string key, object value)
    {
        Session[key] = value;
    }
}
</code>```

By refactoring you have accomplished several things at once.  The program is way more supportive of tearing out underlying structures (you can ditch the database layer for NoSQL), or seamlessly adding locking once you realize Session isn't thread-safe or whatever.  You've also now given yourself very straightfoward tests to write for these three dependencies.

Hope this helps :)

Title: How does unit testing work?

Body:
Unit tests, if you're testing small enough units, are always asserting the blindingly obvious.

The reason that add(x, y) even gets mention of a unit test, is because sometime later somebody will go into add and put special tax logic handling code not realizing that add is used everywhere.

Unit tests are very much about the associative principle: if A does B, and B does C, then A does C.  "A does C" is a higher-level test.  For instance, consider the following, completely legitimate business code:

public void LoginUser (string username, string password) {
    var user = db.FetchUser (username);

    if (user.Password != password)
        throw new Exception ("invalid password");

    var roles = db.FetchRoles (user);

    if (! roles.Contains ("member"))
        throw new Exception ("not a member");

    Session["user"] = user;
}

At first glance this looks like an awesome method to unit test, because it has a very clear purpose.  However, it does about 5 different things.  Each thing has a valid and invalid case, and will make a huge permutation of unit tests.  Ideally this is broken down further:

public void LoginUser (string username, string password) {

    var user = _userRepo.FetchValidUser (username, password);

    _rolesRepo.CheckUserForRole (user, "member");

    _localStorage.StoreValue ("user", user);
}

Now we're down to units.  One unit test does not care what _userRepo considers valid behavior for FetchValidUser, only that it's called.  You can use another test to ensure exactly what a valid user constitutes.  Similarly for CheckUserForRole ... you've decoupled your test from knowing what the Role structure looks like.  You've also decoupled your entire program from being tied strictly to Session.  I imagine all the missing pieces here would look like:

class UserRepository : IUserRepository
{
    public User FetchValidUser (string username, string password)
    {
        var user = db.FetchUser (username);

        if (user.Password != password)
            throw new Exception ("invalid password");

        return user;
    }
}

class RoleRepository : IRoleRepository
{
    public void CheckUserForRole (User user, string role)
    {
        var roles = db.FetchRoles (user);

        if (! roles.Contains (role))
            throw new Exception ("not a member");
    }
}

class SessionStorage : ILocalStorage
{
    public void StoreValue (string key, object value)
    {
        Session[key] = value;
    }
}

By refactoring you have accomplished several things at once.  The program is way more supportive of tearing out underlying structures (you can ditch the database layer for NoSQL), or seamlessly adding locking once you realize Session isn't thread-safe or whatever.  You've also now given yourself very straightfoward tests to write for these three dependencies.

Hope this helps :)


答:
Since nobody else seems to have provided an actual example:

```<code>    public void testRoman() {
        RomanNumeral numeral = new RomanNumeral();
        assert( numeral.toRoman(1) == "I" )
        assert( numeral.toRoman(4) == "IV" )
        assert( numeral.toRoman(5) == "V" )
        assert( numeral.toRoman(9) == "IX" )
        assert( numeral.toRoman(10) == "X" )
    }
    public void testSqrt() {
        assert( sqrt(4) == 2 )
        assert( sqrt(9) == 3 )
    }
</code>```

You say:

I feel that this test is totally useless, because you are required to
  manually compute the wanted result and test it

But the point is that you are much less likely to make a mistake (or at least more likely to notice your mistakes) when doing the manual computations then when coding.

How likely are you to make a mistake in your decimal to roman conversion code? Pretty likely. How likely are you to make a mistake when converting decimal to roman numerals by hand? Not very likely. That's why we test against manual calculations.

How likely are you to make a mistake when implement a square root function? Pretty likely. How likely are you make a mistake when calculating a square root by hand? Probably more likely. But with sqrt, you can use a calculator to get the answers.

FYI I am currently coding mostly "procedural" functions that take ~10
  booleans and a few ints and give me an int result based on this, I
  feel like the only unit testing I could do would be to simply re-code
  the algorithm in the test

So I'm going to speculate about what's happening here. Your functions are kinda complicated, so it is hard to figure out from the inputs what the output should be. In order to do that, you have to manually execute (in your head) the function to figure out what the output is. Understandably, that seems kinda useless and error-prone.

The key is that you want to find the correct outputs. But you have to test those outputs against something known to be correct. Its no good to write your own algorithm to calculate that because that may very well be incorrect. In this case its too hard to manually calculate the values.

I'd go back to the ruby code, and execute these original functions with various parameters. I'd take the results of the ruby code and put those in the unit test. That way you don't have to do the manual calculation. But you are testing against the original code. That should help keep the results the same, but if there are bugs in the original then it won't help you. Basically, you can treat the original code like the calculator in the sqrt example.

If you showed the actual code you are porting we could provide more detailed feedback on how to approach the problem.

Title: How does unit testing work?

Body:
Since nobody else seems to have provided an actual example:

    public void testRoman() {
        RomanNumeral numeral = new RomanNumeral();
        assert( numeral.toRoman(1) == "I" )
        assert( numeral.toRoman(4) == "IV" )
        assert( numeral.toRoman(5) == "V" )
        assert( numeral.toRoman(9) == "IX" )
        assert( numeral.toRoman(10) == "X" )
    }
    public void testSqrt() {
        assert( sqrt(4) == 2 )
        assert( sqrt(9) == 3 )
    }

You say:

I feel that this test is totally useless, because you are required to
  manually compute the wanted result and test it

But the point is that you are much less likely to make a mistake (or at least more likely to notice your mistakes) when doing the manual computations then when coding.

How likely are you to make a mistake in your decimal to roman conversion code? Pretty likely. How likely are you to make a mistake when converting decimal to roman numerals by hand? Not very likely. That's why we test against manual calculations.

How likely are you to make a mistake when implement a square root function? Pretty likely. How likely are you make a mistake when calculating a square root by hand? Probably more likely. But with sqrt, you can use a calculator to get the answers.

FYI I am currently coding mostly "procedural" functions that take ~10
  booleans and a few ints and give me an int result based on this, I
  feel like the only unit testing I could do would be to simply re-code
  the algorithm in the test

So I'm going to speculate about what's happening here. Your functions are kinda complicated, so it is hard to figure out from the inputs what the output should be. In order to do that, you have to manually execute (in your head) the function to figure out what the output is. Understandably, that seems kinda useless and error-prone.

The key is that you want to find the correct outputs. But you have to test those outputs against something known to be correct. Its no good to write your own algorithm to calculate that because that may very well be incorrect. In this case its too hard to manually calculate the values.

I'd go back to the ruby code, and execute these original functions with various parameters. I'd take the results of the ruby code and put those in the unit test. That way you don't have to do the manual calculation. But you are testing against the original code. That should help keep the results the same, but if there are bugs in the original then it won't help you. Basically, you can treat the original code like the calculator in the sqrt example.

If you showed the actual code you are porting we could provide more detailed feedback on how to approach the problem.


问:
Is there any point in distributing separate .NET 3.5 and 4.0 assemblies?
I want to distribute a .NET library that is .NET 3.5 compliant. The library holds references only to external managed libraries that are targeted against .NET 3.5 client profile or lower.
Is there any point in distributing my library as separate .NET 3.5 and 4.0 targeted assembly? </p>

答:
If you build an application that targets 4.0, you can reference your library even if it's targeted to 3.5. There's no need to have a separate version for 4.0. Unless of course, you use features specific to 4.0 such as default method arguments or parallel classes among others.

BTW, using a <3.5 library in 4.0 will not cause any warnings about mixed assemblies (that i know of).


答: Leave them in a namespace that uses the given functionality. "Utils" should refer to something abstract and reusable.</p>

Title: Structuring Visual Studio folders


问:
Multithreaded file copy
There is an utility we have which is used to upload files (and perform other operations on the file) to a network shared location.

The file size tends to vary from a few mb to 500 mb.

A suggestion has come up that we should maybe support multi-threading when uploading the files to the shared location - not required to do it in byte chunks - each thread should pick one file and try to upload.

I am not so sure if multithreading can speed up IO operations like this. Is my hunch valid?

If indeed we are required to build this functionality I was wondering what would be a good design approach for the copy file engine?

Would it make sense to use a tool like robocopy (I read the newer versions support multithreading)?

Edit: Apologies for the delay and missing some vital information.

This utility is built using C# (.Net 2.0) and any future update also has to be using .Net (framework version is not a constraint). The utility is installed on the machines of the users (around 20 all on WinXP). The target share is on Win2k3 server.

Edit 2: have decided to run some tests with a simple application implementing the file upload through TPL. Post this analysis we will decide whether to go ahead or not. Thanks everyone for the help extended.

答:
I work for Data Expedition, Inc. which, as Emmad mentioned, produces
commercial software for this type of scenario.  Multithreaded file transfer
can have benefits, but you have to carefully understand what your performance
bottlenecks are.

Any network path will have at least dozens of hardware and software components
that the data has to pass through.  The slowest of all of them will determine
your speed.  But how you move the data will change how those components
behave.

Lots of background on that here:
http://www.DataExpedition.com/support/notes/tn0009.html

Running parallel TCP's can help when individual TCP speeds are falling far
below the capacities of the network, the disk, and the CPU.

But if you're looking at network speeds of more than tens of megabits per
second, then parallel data transfers will exponentially reduce your disk I/O
due to thrashing the hard-drive.  It can quickly fall to the point where disk
access becomes much slower than the network capacity.  Choosing the right
read/write block size can help, but that will depend on the particular
hardware.  Also keep in mind that Windows XP/2003 has very limited paged-pool memory, which can make it unstable if speeds go over about 200 megabits per second.

On the flip side, if the network is slower than a few tens of megabits per
second, then running many parallel TCP's can push the latency up to the point
where individual sessions begin to slow down or even drop their connections.
Again, its a matter of experimentation to find what level of parallelism will
work for any given path and conditions.

So, multithreaded file copy can help if you have a known data path and can
take the time to fine tune the number of parallel sessions and your disk I/O.
But it does require that you retune whenever conditions change, and can be
disruptive if you overdo it.  That's why we have chosen to avoid parallel
transfers in our own software, just as we avoid TCP.

Title: Multithreaded file copy


答:
Build a web app that works well on the iPhone and Android (ignore standard browsers for now) and take advantage of HTML5's extended features (https://developer.mozilla.org/en/HTML/HTML5) to overcome latency, spotty network, and the limitation of phone browsers. This most likely means delivering a javascript+html5  browser app that connects to a server-based api. (pick xmlrpc/json/yaml, not SOAP). make it screaming fast. On the server, I recommend using cherrypy in linux (debian) on cheap VPS. You can get some at 123systems.com, buyvm.net (preferred but often not available) for under $4 a month. Learn to use Python, and use Fabric to deploy your stuff to your server(s). Get a .info domain at namecheap.com for $2.99 a year, and use dnsmadeasy.com for DNS (more expensive, but worth it-- been using them for years, never had a single issue) where you can do load-balance via DNS. Also, don't be put off by databases. Use sqlite and learn to design your tables manually with sql statements. Finally, with one machine you can probably handle 30,000 users. (2,000 simultaneously at one hit to server every 3 seconds). Remember to cache as much as possible in HTML5's storage.

If you do this, and you blog about it and twit about the blog entries and your progress, you will definitely get noticed. Granted there's a lot to learn, but you can do it!

Title: What's the best place for a high school programmer to get his work noticed?

Body:
I'm a 16 year old high school student, with a passion for computer programming.
I'm in grade 11, and I've been learning it as part of the school syllabus for about 8 months.
I've gone beyond what's being taught at school, and witten a few (reasonably good) applications. The language that I program in is C++, on the windows platform.
Eventually I'd like to major in CS at a good college and then work as a programmer.

The specific questions that I have are:

What is a good place for me to get my work noticed ?

Are there any journals, or publications specifically for young programmers ?

If not publications, then are there any good blogs, or is it just better to start your own ?

Is there anything else, that would help me get noticed as a programmer ?

I've tried to be as objective as possible.

If all this was tl;dr:
What's the best way to get noticed as a young programmer ?

Edit:
I am not looking to get hired straight out of high school
The aim is not to impress the community as a professional programmer.
This is with intent towards college applications where having your work seen and critiqued by other people will improve your application. I am not looking to earn money from what I've written (so far).


问:
What implementation do you use when dealing with operators in .Net?
My question is in a sense a follow up of this post on Time Series in .Net.

Ideally, you would like to expand the basic TimeSeries<T> class by something like NumericTimeSeries<T>, where you would want to make sure that the type T implements the common numerical operators +, -, *, `/', ...

I am not sure what would be the most intelligent way to do this.

My first idea is to create an abstract class Number, with abstract methods Add(Number n1,Number n2), Multiply(Number n1,Number n2), Subtract(Number n1,Number n2), Divide(Number n1,Number n2) (and so on). I would then call these methods in the operator overloads.

I can then create concrete classes such as IntNumber, DoubleNumber, MatrixNumber, ComplexNumber (and so on).

The problem is that in the methods implementation, I would have to make an awful switch to determine what the class of each parameter is, and it's not very elegant.

Would you have done it the same way?

Has something already be done?

In F# I would use and inline functions, or pattern matching using discriminated unions. But what should I do in C#?

EDIT:

There was an awesome answer by Olivier Jacot-Descombes. However, I would like to specify a feature.

The numbers can apply the operator between them (you can multiply a matrix with a scalar for example). The problem with this is that you cannot know in advance the type of the result; multiplying a vector (transposed) and a vector returns a double...

答:
Operator overloading in .Net is wonky, and I would say in this case is more effort than its worth, I would not bother with it. If you don't want to do a bunch of null checks (and who does) -

```<code>return Object.ReferenceEquals(null, leftIntNum) ? //because someone could have always overloaded == and done it wrong
null :
leftIntNum.MultiplyBy(rightIntNum)`
</code>```

You can use extension methods

```<code>  public static NullMultiplyBy<T1, T2>(this T1 numerator, T1 denominator)
   where T1 : Number<T2> {
    return Object.ReferenceEquals(null, numerator) ?
    null :
    numerator.MultiplyBy(rightIntNum)`
  }
</code>```

Other than that, expose an interface, not an abstract class. You can still use an abstract base class, but avoid referencing it in your method signatures.

Body:
Operator overloading in .Net is wonky, and I would say in this case is more effort than its worth, I would not bother with it. If you don't want to do a bunch of null checks (and who does) -

return Object.ReferenceEquals(null, leftIntNum) ? //because someone could have always overloaded == and done it wrong
null :
leftIntNum.MultiplyBy(rightIntNum)`

You can use extension methods

  public static NullMultiplyBy<T1, T2>(this T1 numerator, T1 denominator)
   where T1 : Number<T2> {
    return Object.ReferenceEquals(null, numerator) ?
    null :
    numerator.MultiplyBy(rightIntNum)`
  }

Other than that, expose an interface, not an abstract class. You can still use an abstract base class, but avoid referencing it in your method signatures.


问:
Can you learn OO programming without procedural?
I've seen a number of question asking whether someone should learn procedural or OO first. But is this even possible? Can you learn OO programming without first having an understanding of procedural programming? Obviously, they can learn to program in an OO language like Java or Python first. But you can write Fortran in any language. My impression is that such beginning programmers write procedural code in an OO language at least at first.

But what do you think?

答:
If you're programming in a purely object-oriented language such as Eiffel, Smalltalk, or Ruby then you're probably going to be forced to learn object-oriented programming from the get-go (as it's effectively the cornerstone of the language) (also note that these languages often have support for other types of programming, such as functional, etc.).

Now, having said that, both object-oriented and procedural programming are ultimately derived from the imperative paradigm, effectively describing how the program is meant to accomplish its task. As such, you still use certain procedural ideas in your program.

In languages that are hybrids (and not fully object-oriented), such as Java, you will still see a lot of object-oriented programming (as it's very relevant in the programming field today, also, Java is routinely used to teach object-oriented concepts).

Bottom line: you don't need to spend years (or even months) learning the procedural paradigm to be capable of understanding the object-oriented paradigm. You can start learning the object-oriented paradigm from the get-go (and you'll doubtlessly pick up certain procedural concepts as you go).


问:
What is MVC, really?
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

答:
MVC is a design pattern used to isolate business logic from presentation.

It differs from a lot of other design patterns by the fact that it usually isn't implemented succinctly, but is the base of a framework.

While an application implementing a Strategy pattern is just a small detail about it, saying that a web app uses the MVC design pattern is very defining of its architecture.

Title: What is MVC, really?


答:
I don't recommend that you "try" OO without formal support (a good book, a helpful website, formal schooling, or a human mentor).

You can easily "try" Procedural without any help - the way you think about how to solve a problem will likely be in a step-wise fashion. This coencides well with procedural programming, so it flows more or less naturally from your thoughts on how to solve a given programming problem.

But "OO" is another animal, a very different way of organizing, abstracting and hiding the implementation of solution, and thus requires a different way of thinking about a problem.  You might need some help/a mentor/a good book/formal training to get started in OO.

Setting aside all other concerns for a moment, and considering your question purely from a career-based perspective - If you want a job as a professional software developer you will have greater marketability if you possess OO skills.

If you only want to write code for fun, you can use whatever is easiest/more enjoyable for you.

If you want a career as a software developer, might as well bite the bullet and start with OO - and make sure to get that formal support that I mentioned!

Title: Can you learn OO programming without procedural?

Body:
I've seen a number of question asking whether someone should learn procedural or OO first. But is this even possible? Can you learn OO programming without first having an understanding of procedural programming? Obviously, they can learn to program in an OO language like Java or Python first. But you can write Fortran in any language. My impression is that such beginning programmers write procedural code in an OO language at least at first.

But what do you think?


问:
Using Cucumber with Page objects
We are using Cucumber in our application after we previously used Selenium. Cucumber is far better than Selenium, but it may seem to be complicated since has to write gherkin, step definitions may be page objects.

We are using Celerity with JRuby. The flow is: 'gherkin' calls 'Step definition' calls 'Page objects'.

On one hand, every QA tester writing Cucumber tests will have to be familiar with Ruby in order to use page objects, but on the other hand, we can avoid code duplication and repeatedly broken tests.

What are the pros and cons of using page objects with Cucumber? Should we stop worrying about duplicate code in tests and stick with using step definitions instead of page objects?

答:
Actually, cucumber has nothing to do with "pages". The page object itself comes with capybara. In case you intend to use cucumber + capybara for testing web pages you have to use the page object, so there are no cons. Additionally, you always have to worry about duplication in case of test cases, but it is a completely different issue.

The structure in nutshell: cucumber scenario -> step definition(s) -> capybara pages. In the background capybara will use the appropriate selenium drivers.

HTH

ContentLicense: CC BY-SA 4.0

Title: Using Cucumber with Page objects


答:
MVC is a software architecture - the structure of the system - that separates domain/application/business (whatever you prefer) logic from the rest of the user interface. It does this by separating the application into three parts: the model, the view, and the controller.

The model manages fundamental behaviors and data of the application. It can respond to requests for information, respond to instructions to change the state of its information, and even to notify observers in event-driven systems when information changes. This could be a database, or any number of data structures or storage systems. In short, it is the data and data-management of the application.

The view effectively provides the user interface element of the application. It'll render data from the model into a form that is suitable for the user interface.

The controller receives user input and makes calls to model objects and the view to perform appropriate actions.

All in all, these three components work together to create the three basic components of MVC.

Title: What is MVC, really?

Body:
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?


问:
C++ users proposals
I believe I have some good suggestions to improve the C++ language. Who should I contact to discuss this? Do I have the chance to be heard, especially if I'm not a renowned expert?</p>

答:
According to this page on the C++ committee's official web site:

The public can submit proposed defect reports via the Internet news
  group comp.std.c++

You can access comp.std.c++ via groups.google.com, but it's better to get an account on an actual NNTP server (I use news.eternal-september.org, which is free of charge) and use a new client (Thunderbird does this; I use Gnus under Emacs myself).

I recommend browsing the group before posting, just to get a feel for how it works.

Note that revisions of the standard only come out every few years, and a new one was just published on 2011-09-11.  I don't know what, if any, work has started on a new revision.

Title: C++ users proposals


问:
What would be the best way to manage a lot of jQuery code?
Sorry for the blunt question, I will try to explain further.

I am going to have a website which uses jQuery, and I feel that at some point in time, there will be A LOT of jQuery code, meaning A LOT of functions, jQuery selectors, etc. Is there a way to limit the availability of jQuery code for specific pages? Perhaps using objects? I'm looking for the best approach here so I don't just run off into a storm and can't find my way out.

Thanks.

答:
I normally separate my code in a modular fashion where each part of the page (each module) gets its own file for CSS, JS and HTML (as well as PHP/whatever server side code you use).

Each module is wrapped in a div or section (or whatever's semantic) element with a unique (obviously) ID, like this:

```<code><section id="recent-comments">

    <h2>Recent comments</h2>

    <ul>
        ...
    </ul>

</section>
</code>```

Then I create a CSS file named after the module (recent-comments.css) and a JS file (recent-comments.js). The JS-file can look something like this:

```<code>Base.modules.RecentComments = {
    init: function () {
        this.autoRefreshComments(); // this is just an example
    },

    autoRefreshComments: function () {
        setInterval(function () {
            $('#recent-comments').load('/new-comments');
        }, 5000);
    }
};
</code>```

If I start writing code in a module file that I think can be re-used I usually turn it into a jQuery plug-in (that can be re-used).

This leads to plenty of different CSS and JS-files but of course I merge them all into one before serving them to the browser.

The benefit of this is that you can very quickly find code related to one part of your page and your files are normally kept pretty short and concise.

I used to serve different JS/CSS for each page (only the modules that were in use on that page) but I don't think it improves performance as it leads to one unique CSS and JS files per page instead of just one CSS and JS file that is cached on the first page load.

Edit: btw, this is what the Base "class" would look like:

```<code>var Base = {
    modules: [],

    init: function () {
        Base.runModules();
    },

    runModules: function () {
        for (var module in Base.modules) {
            // Work out the HTML-ID based on the module-name (RecentComments == recent-comments)
            var id      = module.replace(/([A-Z])/g, '-$1').toLowerCase();
                id      = id.substring(0, 1) == '-' ? id.substring(1) : id;
            var mod     = jQuery('#' + id);

            if (
                    mod.length &&
                    typeof(Base.modules[module]) != 'undefined' &&
                    typeof(Base.modules[module].init) == 'function'
            ) {

                Base.modules[module].init(mod);
            }
        }
    }
};

$(Base.init);
</code>```

OwnerDisplayName: zzatkin

Body:
I normally separate my code in a modular fashion where each part of the page (each module) gets its own file for CSS, JS and HTML (as well as PHP/whatever server side code you use).

Each module is wrapped in a div or section (or whatever's semantic) element with a unique (obviously) ID, like this:

<section id="recent-comments">

    <h2>Recent comments</h2>

    <ul>
        ...
    </ul>

</section>

Then I create a CSS file named after the module (recent-comments.css) and a JS file (recent-comments.js). The JS-file can look something like this:

Base.modules.RecentComments = {
    init: function () {
        this.autoRefreshComments(); // this is just an example
    },

    autoRefreshComments: function () {
        setInterval(function () {
            $('#recent-comments').load('/new-comments');
        }, 5000);
    }
};

If I start writing code in a module file that I think can be re-used I usually turn it into a jQuery plug-in (that can be re-used).

This leads to plenty of different CSS and JS-files but of course I merge them all into one before serving them to the browser.

The benefit of this is that you can very quickly find code related to one part of your page and your files are normally kept pretty short and concise.

I used to serve different JS/CSS for each page (only the modules that were in use on that page) but I don't think it improves performance as it leads to one unique CSS and JS files per page instead of just one CSS and JS file that is cached on the first page load.

Edit: btw, this is what the Base "class" would look like:

var Base = {
    modules: [],

    init: function () {
        Base.runModules();
    },

    runModules: function () {
        for (var module in Base.modules) {
            // Work out the HTML-ID based on the module-name (RecentComments == recent-comments)
            var id      = module.replace(/([A-Z])/g, '-$1').toLowerCase();
                id      = id.substring(0, 1) == '-' ? id.substring(1) : id;
            var mod     = jQuery('#' + id);

            if (
                    mod.length &&
                    typeof(Base.modules[module]) != 'undefined' &&
                    typeof(Base.modules[module].init) == 'function'
            ) {

                Base.modules[module].init(mod);
            }
        }
    }
};

$(Base.init);

OwnerDisplayName: powerbuoy


答:
You have a 100% "chance to be heard," but you should be aware that the goals for the C and C++ language standards are quite conservative. There's billions of lines of C and C++ code out there and breaking changes are viewed with extreme reluctance. And, like any long-lived group, they probably are a little suspicious about new voices. As @Keith Thompson suggested, you should probably start with the NNTP groups, just to get a sense of the technical level of discussion.

Depending on how radical your changes are, the wisest thing to do might be to gather your changes and implement them under a new name and see if they gain any traction. Once they've been tested and their interaction with the broad world of C and C++ code is understood, you'd have a better chance of having them incorporated into the language.

(And note that the C committee doesn't have the same relationship with comp.std.c that the C++ committee has with comp.std.c++.  But comp.std.c.is still a good place to get feedback on any proposals for the C standard -- as long as you're aware that there's nothing official about it.)

Title: C++ users proposals

Body: I believe I have some good suggestions to improve the C++ language. Who should I contact to discuss this? Do I have the chance to be heard, especially if I'm not a renowned expert?</p>


答:
The best way to define it is to go to the original writings of Trygve Reenskaug, who invented it: http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html

This paper, in particular, is generally considered the definitional text: http://heim.ifi.uio.no/~trygver/1979/mvc-2/1979-12-MVC.pdf

MODELS

Models represent knowledge. A model could be a single object (rather uninteresting), or it could be some structure of objects...

There should be a one-to-one correspondence between the model and its parts on the one hand, and the represented world as perceived by the owner of the model on the other hand. The nodes of a model should therefore represent an identifiable part of the problem.

The nodes of a model should all be on the same problem level, it is confusing and considered bad form to mix problem-oriented nodes (e.g. calendar appointments) with implementation details (e.g. paragraphs).

VIEWS

A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. It is thus acting as a presentation filter.

A view is attached to its model (or model part) and gets the data necessary for the presentation from the model by asking questions. It may also update the model by sending appropriate messages. All these questions and messages have to be in the terminology of the model, the view will therefore have to know the semantics of the attributes of the model it represents. (It may, for example, ask for the model's identifier and expect an instance of Text, it may not assume that the model is of class Text.)

CONTROLLERS

A controller is the link between a user and the system. It provides the user with input by arranging for relevant views to present themselves in appropriate places on the screen. It provides means for user output by presenting the user with menus or other means of giving commands and data. The controller receives such user output, translates it into the appropriate messages and pass these messages on .to one or more of the views.

A controller should never supplement the views, it should for example never connect the views of nodes by drawing arrows between them.

Conversely, a view should never know about user input, such as mouse operations and keystrokes. It should always be possible to write a method in a controller that sends messages to views which exactly reproduce any sequence of user commands.

EDITORS

A controller is connected to all its views, they are called the parts of the controller. Some views provide a special controller, an editor, that permits the user to modify the information that is presented by the view. Such editors may be spliced into the path between the controller and its view, and will act as an extension of the controller. Once the editing process is completed, the editor is removed from the path and discarded.

Note that an editor communicates with the user through the metaphors of the connected view, the editor is therefore closely associated with the view. A controller will get hold of an editor by asking the view for it - there is no other appropriate source.

Title: What is MVC, really?


问:
Why do some sorting methods sort by 1, 10, 2, 3...?
I've noticed than many numerical sorting methods seem to sort by 1, 10, 2, 3... rather than the expected 1, 2, 3, 10... I'm having trouble coming up with a scenario where I would need the first method and, as a user, I get frustrated whenever I see it in practice. Are there legitimate use cases for the first style over the second? If so, what are they? If not, how did the first sort style ever come into being? What are the official names for each sort method?</p>

答:
That's the result when you sort strings of numbers alphabetically instead of numerically.

That sort style is the default behavior of the unix sort command for example, unless you use the --numeric-sort command line option, which tells it to attempt to interpret the numeric values.


答:
Alphabetically, 1 comes before 2.  Whenever you see the first method, it's not because it's desirable, but because the sorting is strictly alphabetical (and happens left-to-right, one character at a time): 1, 2, 10 makes sense to you but not to a computer that only knows alphabetic comparison. There's no way in that kind of simple comparison to know that a one followed by a 0 actually comes after a two.

When you see mixed word and number sorting that treats numbers correctly, it's because the sorting is more intelligent, and on top of that, still usually only works at the beginning or end of a string.

Title: Why do some sorting methods sort by 1, 10, 2, 3...?

Body: I've noticed than many numerical sorting methods seem to sort by 1, 10, 2, 3... rather than the expected 1, 2, 3, 10... I'm having trouble coming up with a scenario where I would need the first method and, as a user, I get frustrated whenever I see it in practice. Are there legitimate use cases for the first style over the second? If so, what are they? If not, how did the first sort style ever come into being? What are the official names for each sort method?</p>


答:
that is lexicographic sorting which means basically the language treats the variables as strings and compares character by character ("200" is greater than "19999" because '2' is greater than '1')

to fix this you can

ensure that the values are treated as integers,

prepend '0' to the strings so all have equal lengths (only viable when you know the max value).

This is why you'll see episode numberings on media files (S1E01) with a prepended 0 so a lexicographic sort doesn't mess things up and allows programs to simply play/display in alphabetical order,

or make a custom comparator that first compares the length of the strings (shorter strings being smaller integers) and when they are equal compare the lexicographically (careful about leading '0')


答:
MVC is mostly a buzzword.

It used to be considered a pattern, but its original 1979 definition has been dumbed down, passed on, misinterpreted, and taken out of the original context. It's been ill-redefined to the point it starts resembling a religion, and while this certainly helps its cargo cultists defending it, its name doesn't associate anymore with a solid set of guidelines. As such, it cannot really be considered a pattern anymore.

MVC was never meant to describe web applications.
Nor modern operating systems, nor languages
(some of whom actually made the 1979 definition redundant).

It was made to. And it didn't work out.

We now deal with an obscene web-mvc hybrid that, with its awful buzzword status, ill definition, and having semi-illiterate-programmers as a target demographic, makes a really bad publicity to software patterns in general.

MVC, thus, became separation of concerns distilled for people who don't really want to think too much about it.

The data model is handled  one way,

the view in another,

the rest is just named "controller" and left to the reader's discretion.

Web sites / web applications in the 1990s did not really use to apply separation of concerns.

They were horrible botches of intermixed spaghetti code.
UI changes, redesigns, and data rearrangements were incredibly hard, expensive, long, depressing, and ill-fated.

Web technologies like ASP, JSP and PHP made it too easy to intermix view concerns with data and application concerns. Newcomers to the field usually emit inextricable code mudballs like in those old times.

Thus, a growing number of people started repeating "use MVC" in endless loops on support forums. The number of people expanded to the point of including managers and marketers, (to some the term was already familiar, from those times in GUI programming, in which the pattern made sense) and that became the behemoth of a buzzword we have to face now.

As it stands, it's common sense, not a methodology.
It's a starting point, not a solution.
It's like telling people to breathe air, or make crunches, not a cure for cancer.

Title: What is MVC, really?


答:
OO is an extension of the procedural paradigm.

You can learn to program in OO without being able to code non-trivial-to-complex programs in procedural languages, but the theoretical bases behind procedural are inevitable.

You wouldn't know:

how to use globals effectively,

what static C variables are for,

what primitive types really are for and will always push to deal with the equivalent object types.

You would indulge in:

defining class variables,

throwing in redundant objects,

thinking hierarchically,

abusing inheritance,

denying that objects may cause overhead (performance-wise, but also on the organizational level)


答:
What makes something object-oriented? You might produce a list of things that characterize the paradigm, here is a list derived from wikipedia:

data abstraction

encapsulation

messaging

modularity

polymorphism

inheritance

But no language forces to use these things. You can write procedural Java. Using the class keyword doesn't make your code OO. OO is really about the way you structure the design of your system. Many programs written in pure OO language are not structured in anything like an OO way. Many programs written in non-OO languages are structured in an OO way.

If you look at a beginner's code you'll see that do a terrible job of pretty much everything in that OO list. Their code will work, but it is not pretty. (I've written some pretty terrible stuff myself, and it stubbornly stays in production). They've grasped the basics, the procedural part, but they really haven't grasped OO programming.

Basically, you can't really grasp the idea of encapsulation until you've first grasped variables, loops, functions, etc. That's why I think you have to learn procedural before you can learn OO.