答:
If you already worked with Zend, stick with it. There are other Frameworks and (depending on your case) some might fit better than others. But if you dont have any major showstopper whithin Zend, then why switch? Dont switch because "you have read in some blog that said X". </p>

<p>Writing (and maintaining!) your own framework, will propably not be worth the effort. If you dont like the Zend Way try other Frameworks, but dont invent the 74.259's php web framework. =) </p>

Title: Should we stick to a framework?

Body: I currently work with Zend Framework, but I also know about CodeIgniter and Kohana. I've just wonder that should I stick to a framework or depend on my purposes? Because I think I cannot master everything.</p>

Body:
If you already worked with Zend, stick with it. There are other Frameworks and (depending on your case) some might fit better than others. But if you dont have any major showstopper whithin Zend, then why switch? Dont switch because "you have read in some blog that said X".

Writing (and maintaining!) your own framework, will propably not be worth the effort. If you dont like the Zend Way try other Frameworks, but dont invent the 74.259's php web framework. =)


问:
Are design patterns generally a force for good or bad?
I've heard it argued that design patterns are the best thing since sliced bread.  I've also heard it argued that design patterns tend to exacerbate "Second System Syndrome," that they are massively overused, and that they make their users think they're better designers than they really are.

I tend to fall closer to the former camp, but recently I've been seeing designs where nearly every single interaction is replaced with an observer relationship, and everything's a singleton.

So, considering the benefits and problems, are design patterns generally good or bad, and why?

答:
Using an analogy to money, a design pattern should be thought of as a solution with high capital cost but low operating costs.  Design patterns cost a fortune upfront in terms of extra coding, verboseness and the conceptual weight from the extra indirection they create.  They also have a tendency to lock down other aspects of your design.  For example, using template method forces you to program in a heavily OO style.

However, if you need to solve a lot of closely related problems that vary in some small ways, or are definitely going to need to modify a piece of code heavily in some specific ways in the future, the upfront costs can be worth it because design patterns add flexibility to your code.  The modifications or the solution to the second of your set of closely related problems will be a lot easier with patterns than without.

ContentLicense: CC BY-SA 2.5


问:
How important is learning Algorithms for high level language programmers

Possible Duplicate:

  How important is studying algorithms and theory is to becoming a great programmer?

Today I learned the fast sort Algorithm. I doubt I will ever implement my own version though as C# has its own built in Sort method for lists and arrays.

How important is learning Algorithms for high level language programmers? In my example I gained no benifit from knowing the Algorithm but perhaps my example was too trivial to be accurate?

答: You know you will not always write trivial code, at some point in your projects you will have to write an algorithm that solves a hard problem for example matching objects with each other according to some data. And when you do that, you will have in mind the complexity of an algorithm so the solution you come up with will have a perspective of an algorithm designer in it. </p>

ContentLicense: CC BY-SA 3.0


答:
Which sort algorithm did you learn?  Quicksort, heapsort, bucket sort, insertion sort, radix sort, bubble sort, or a bunch of possible others?  Which sorting algorithm does C# use?

What I'm getting at is that there are many possible strategies for many algorithms and data structures (containers are another good example) that each have their own benefits and drawbacks.  Any single "generic" implementation will have made a specific choice regarding those benefits and drawbacks - and that choice may not be optimal for your particular problem.

Now, that may not be an issue, as you don't want to prematurely optimize anyway, but being unaware of these choices, drawbacks and benefits leaves you a gaping blind spot in your well-roundedness as a developer.

Body:
Possible Duplicate:

  How important is studying algorithms and theory is to becoming a great programmer?

Today I learned the fast sort Algorithm. I doubt I will ever implement my own version though as C# has its own built in Sort method for lists and arrays.

How important is learning Algorithms for high level language programmers? In my example I gained no benifit from knowing the Algorithm but perhaps my example was too trivial to be accurate?


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

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

View existing ledger entries in table format.

Create new ledger entry using create button.

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

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

So I decided to create three different classes -

LedgerLandingPage

CreateNewLedgerEntryPage

ViewLedgerEntryPage

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

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

答:
Do those classes have only one reason to change?

If you do not know it (yet), then you might have stepped into the speculative design / over engineering trap (too many classes, too complex design patterns applied). You have not satisfied YAGNI. In early stages of the software life cycle (some) requirements might be not clear. Thus the direction of change is currently not visible for you. If you realize that, keep it in one or a minimal amount of classes. However this comes with a liability: As soon as the requirements and the direction of change are clearer you need to rethink the current design and make a refactoring to satisfy the reason of change.

If you already know that there are three different reasons for change and that they map to those three classes, then you just applied the right dose of SRP. Again this comes with some liability: If you are wrong or future requirements change unexpectedly, you need to rethink the current design and make a refactoring to satisfy the reason of change.

The whole point is:

Keep an eye on the drivers for change.

Chose a flexible design, which can be refactored.

Be ready to refactor code.

If you have this mindset, you will shape the code without much fear of speculative design / over engineering.

However there is always the factor time: For many changes you will not have the time you need. Refactoring costs time and effort. I often encountered situations where I knew I had to change the design, but due to time constraints I had to postpone it. This will happen and cannot be avoided. I found that it is easier to refactor under engineered code than over engineered code. YAGNI gives me a good guideline: If in doubt, keep the amount of classes and the application of design patterns to a minimum.


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答: Just a quick suggestion. Whenever I have a programming problem that needs to be solved or debug I like to look at my code and 'play computer' where In my head I keep track of the variables and their values and what I expect them to be when each line is run. So if I copied some code from somewhere, unless it is complete on it's own and I just need to reference it, I like to go line by line to understand exactly what is going on. Essentially playing computer. VBA Debugger essentially makes this task easier but making your students do it on paper might give them fundamentals like. What does this line actually do?</p>


问:
Count a row VS Save the Row count after each update
I want to know whether saving row count in a table is better than counting it each time of the proccess.

Quick Example : A visitor goes to Group Clan, the page displays clan information and Members who have joined the group,Should the page look for all the users who joined the clan and count them, or just display the number of members already saved in table ?

I think the first one is not possible to get manipulated with but IT MIGHT cost performance

Your Ideas ?

答: you are optimizing the wrong thing :), your group page is not very likely to change so what you really want to do is cache the complete html-output and return your group page from the cache which leads to zero db round-trips and therefor much more performance gain then an optimized db-query</p>


问:
CSS and HTML inconsistent when declaring multiple classes
I'm learning CSS "seriously" for the first time, but I've found that the way you deal with multiple CSS classes in CSS and HTML quite inconsistent.

For example, I learned that if I want to declare multiple CSS classes with a common style applied to them, I write:

```<code>.style1, .style2, .style3 {
   color: red;
}
</code>```

Then, if I want to declare an HTML tag that has multiple classes applied to it, I write:

```<code><div class="style1 style2 style3"></div>
</code>```

And I'm asking why? From my personal point of view it would be more consistent if both could be declared by using a comma to separate each class, or if both could be declared using a space; after all IMHO we're still talking about multiple classes, in both CSS and HTML. I think that it would make more sense if I could write this to declare a div with multiple classes applied:

```<code><div class="style1, style2, style3"></div>
</code>```

Am I'm missing something important? Could you explain me if there's a valid reason behind these two different syntaxes?

答:
(I presume you meant to say .style1 .style2 .style3 in your CSS example, otherwise you're referring to tag names.)

In CSS, .style1 .style2 means something completely different from .style1, .style2: the first only applies an element to which has both style1 and style2 classes, the second applies to both style1 and style2 individually. That distinction is vital (don't forget the C in CSS means "cascading"), so there shouldn't be a way of eliminating the need for the comma.

Now, as to why you can't use commas in the HTML element, you may well have a point: unfortunately it's too late to do anything about it.


答:
I suggest the following:
- Don't display the data if it is not accurate.
- If you are worried about performance, display accurate information only based on request
- There are ways to get accurate counts cheaply for example consider either of these approaches:

1 - Count function can run against the database meta data and does not count rows (depending on your database)

2 - Use the concept of Materialized View (as in Oracle) (called Indexed View in SQL Server). While MySQL does not support this directly, it may be simulated - See this: MySQL-Simulate Materialized Views

Title: Count a row VS Save the Row count after each update

Body:
I want to know whether saving row count in a table is better than counting it each time of the proccess.

Quick Example : A visitor goes to Group Clan, the page displays clan information and Members who have joined the group,Should the page look for all the users who joined the clan and count them, or just display the number of members already saved in table ?

I think the first one is not possible to get manipulated with but IT MIGHT cost performance

Your Ideas ?


答:
I do not think that for a high level language programmer learning algorithms is important for being productive. It is like knowledge about how the compiler works, how the garbage collector works, how a finite state machine works, why floating point operations can lead to wrong calculation results, how ASCII is different from UTF-8 and so on and so on.

High level languages, which deliberately hide such low level stuff from the programmer, want to give you the possibility to concentrate on business rules. I have seen many programmers lacking of "low level" knowledge and still get their work right.

Like a mechanic can get the most out of his car than an ordinary car driver, a programmer with (at least some) "low level" knowledge will make better decisions. For sorting algorithms this means for example: If you know that that the data is partly sorted then you will likely choose Bubble sort. The programmer guy next to you, who does not know this, might choose a slower algorithm. Will he get his work done: Yes. Will he be able to explain the stakeholders if he can make the sorting faster? Maybe not.

However: Does it matter? For most applications which are programmed with a high level programming language, it rarely matters. But in those rare cases, wrong decisions can have devastating consequences. The wrong sorting algorithm will make your program slow, the wrong decision over the character encoding will make in internationalization impossible, and the wrong number type lead to wrong calculation results.

So it is up to you: Do you want to be productive or do you also want to make the right decisions?

Title: How important is learning Algorithms for high level language programmers


答: Learning algorithms (and, last but not least, data structures) is most important. Even if you should of course use the sort function of your language's library, you then know that sorting is comparatively not a cheap operation, hence you will write your code so that sorting is done in the right moment.</p>


答: Both camps are correct - they're a force for good when used correctly, a force for bad if they're splattered all over the place.</p>

Title: Are design patterns generally a force for good or bad?

Body:
I've heard it argued that design patterns are the best thing since sliced bread.  I've also heard it argued that design patterns tend to exacerbate "Second System Syndrome," that they are massively overused, and that they make their users think they're better designers than they really are.

I tend to fall closer to the former camp, but recently I've been seeing designs where nearly every single interaction is replaced with an observer relationship, and everything's a singleton.

So, considering the benefits and problems, are design patterns generally good or bad, and why?


答: You would not use a C# built in Sort method (or anything else for that matter) without knowing what it does and how it goes about doing it, in all its detail -- that is just not being a programmer. You could be an excellent coding help to a programmer, though.</p>


答:
I doubt I will ever implement my own version though as C# has its own built in Sort method for lists and arrays.

Let's say you need a fast median algorithm. Few standard libraries I'm aware of have such a thing built-in. But if you know how quicksort works, it's very simple to modify it to get an algorithm for finding the median in O(n) time. My point is: Algorithms&data structures often have to be modified for a specific problem, and to be able to do that, you need to know and understand them.


问:
What should I put in comments while commiting to the Source Control?
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?

答:
Commit comments are about seeing easily what was changed. They are there for your reference, so how much detail that you put in them will depend on how much effort you want to spend now to save you time in the future. Generally speaking, a little effort at commit time has the potential to save a lot of time in the future.

For instance, say to changed a <= to a > and a ++ to a -- in a loop, but didn't add a descriptive commit comment. Later, it would be difficult to find the revision where you reversed the direction of the iteration. If you'd commented "Reversed direction of blah index traversal" then it would be much easier to find that revision by searching the revision log.

This is why including issue tracking information in commit messages is a really good idea. Say you fix a bug, then later the issue is re-opened because it wasn't completely fixed. If your commit comment of the original fix mentioned the issue tracker identifier, you can easily find it and later still you can easily find all revisions associated with that issue.


问:
Should we stick to a framework?
I currently work with Zend Framework, but I also know about CodeIgniter and Kohana. I've just wonder that should I stick to a framework or depend on my purposes? Because I think I cannot master everything.</p>

答:
If you can master Zend (or Symfony) then smaller frameworks are generally easier to pick up. I personally wouldn't use Zend for anything below a certain size/scope - things like Fat3 or Fuel are ideal for brochure sites, whereas CI and Kohana are intended for mid-scale sites like blogs. I would also recommend taking a look at YAF, an MVC extension for PHP - it's got virtually no docs at the moment but it'll run significantly faster than a script based framework.

As an aside, I think there's a lot of value in writing your own framework (once you've used a couple), purely for academic purposes to give you a greater depth of understanding of MVC. But please don't release it...

Title: Should we stick to a framework?


问:
Django as Python extension?
I come from php community and just started learning Python. I have to create server-side scripts that manipulate databases, files, and send emails.

Some of it I found hard to do in python, comparing to php, like sending emails and querying databases.

Where in php you have functions like mysql_query(), or email(), in python you have to write whole bunch of code. Recently I found Django, and my question is: is it a good framework for network-oriented scripts, instead of using it as a web-framework?

答:
If you are still using mysql_* functions, your PHP skills are extremely outdated.

mysql_* are essentially deprecated since mysqli_* functions came to be, and even mysqli_* has long been surpassed by PDO. Also there's no email() function, but mail(). This may just be a typo in the question, if it is please ignore me.

Now as for the core of your question: (Almost) Everything that's available "out of the box" in PHP is also available in Python. You have to dig a little deeper into Python, before assuming a feature doesn't exist, your examples are pretty basic and a simple search on StackOverflow or Python's online documentation would have sufficed.

Although I'm primarily a PHP developer, I'm not advocating PHP over Python. Both are beautiful languages (in their own ways), with vibrant communities and healthy and stable ecosystems. And both are great for web development. You should choose the one that helps you be more productive, the one you find more fun to work with.

As for Django: It's a framework for web applications, based on the MVC pattern. It's a Python equivalent to PHP frameworks like Zend Framework, Kohana, CodeIgniter, Symfony and others.

You should use it when building Python applications that would require you to use an MVC framework if you were building them in PHP. So if your network-oriented PHP scripts don't use an MVC framework, Django probably won't be good fit either.

Title: Django as Python extension?


问:
A good substitute for ASMX web service methods, but not a general handler
The best thing I like about ASP.NET MVC, is that you can directly call a server method (called action), from the client. This is so convenient, and so straightforward, that I really like to implement such a model in ASP.NET WebForms too.

However, in ASP.NET WebForms, to call a server method from the client, you should either use Page Methods, or Web Services, both of which use SOAP as their communication protocol (though JSON can also be used).

There is also another substitution, which is using Generic Handlers. The problem with them however is that, a separate Generic Handler should be written for each server method. In other words, each Generic Handler works like a simple method.

Is there anyway else to imitate MVC model in ASP.NET WebForms?

Please note that I can't change to MVC platform right now, cause the project at our hand is a big project and we don't have required resources and time to change our platform. What we seek, is a simple MVC model implementation for our AJAX calls. A problem that we have with Web Services, is the known problem of SoapException, and we're not interested in creating custom SoapExctensions.

答:
You probably pant to check out the wcf web API. Preview 6 dropped yesterday, it looks real promising. If you can't get as experimental as that, one can make WCF web services return POX or JSON rather than SOAP. </p>

<p>You can also integrate MVC into traditional web forms apps without too much trouble. Personally, I like mcv handlers better than traditional services. Though the wcf web API is changing my mind fast. </p>

Body:
You probably pant to check out the wcf web API. Preview 6 dropped yesterday, it looks real promising. If you can't get as experimental as that, one can make WCF web services return POX or JSON rather than SOAP.

You can also integrate MVC into traditional web forms apps without too much trouble. Personally, I like mcv handlers better than traditional services. Though the wcf web API is changing my mind fast.


问:
I want to write a 2-player web-based board game. Which framework should I use?
I am a C# software developer.  I was recently approached by a client to develop a multiplayer board game (max 4 players).  I fiddled around with WCF, WPF and EF 4.1 to get something going but I keep running into small stumbling blocks.  It certainly does appear that integrating all these technologies into one solution is problematic.

I do not have extensive experience in WPF/WCF but I find the concepts easy to grasp.  It's just that I keep running into little problems which are huge stumbling blocks.

My thoughts were to first create a WCF service to manage the boards and rules.  I would then turn to the UI (possibly Silverlight/WPF).

I am actually at the point where I think I should try a framework or even venture to PHP/Ruby/Python.

The requirements are simple:

Web based

Turn based

Board game

Database backend

As a C# developer (possibly a poor one), what would you suggest?

答: It's not C# but for a web game, I'd suggest you look into www.stencyl.com for UI, socket.io for communicating with server and node.js as a server. Stencyl is authoring tool for Flash now, but they have HTML5 platform in their roadmap as well, so when Flash declines more, you can switch your UI to native HTML5.</p>


答:
My preference has been to use a Generic Handler that has a parameter indicating the name of the action being taken and a separate parameter with a delineated list of arguments to be sent  along with it. This allows me to identify my action methods in a library and call them either in case statements or reflectively. While reflection is usually a large performance hit, I find that in this scenario it is not significant enough to cause problems. Below is untested psuedo-code that is sort of a break-down of what I've used previously.</p>

```<code>public class MyGenericHandler : IHttpHandler

    public void ProcessRequest(HttpContext context)
    {
        string action = context.Request.QueryString["action"];
        string[] args = context.Request.QueryString["args"].Split("|");

        MyController controller = new MyController();  // whatever your controller class is
        MethodInfo mi = controller.GetType().GetMethod(action);

        if (mi != null)
        {
            context.Response.ContentType = "text/html"
            context.Response.Write(mi.Invoke(controller, args));
        }
    }

}
</code>```

Title: A good substitute for ASMX web service methods, but not a general handler

Body:
The best thing I like about ASP.NET MVC, is that you can directly call a server method (called action), from the client. This is so convenient, and so straightforward, that I really like to implement such a model in ASP.NET WebForms too.

However, in ASP.NET WebForms, to call a server method from the client, you should either use Page Methods, or Web Services, both of which use SOAP as their communication protocol (though JSON can also be used).

There is also another substitution, which is using Generic Handlers. The problem with them however is that, a separate Generic Handler should be written for each server method. In other words, each Generic Handler works like a simple method.

Is there anyway else to imitate MVC model in ASP.NET WebForms?

Please note that I can't change to MVC platform right now, cause the project at our hand is a big project and we don't have required resources and time to change our platform. What we seek, is a simple MVC model implementation for our AJAX calls. A problem that we have with Web Services, is the known problem of SoapException, and we're not interested in creating custom SoapExctensions.

Body:
My preference has been to use a Generic Handler that has a parameter indicating the name of the action being taken and a separate parameter with a delineated list of arguments to be sent  along with it. This allows me to identify my action methods in a library and call them either in case statements or reflectively. While reflection is usually a large performance hit, I find that in this scenario it is not significant enough to cause problems. Below is untested psuedo-code that is sort of a break-down of what I've used previously.

public class MyGenericHandler : IHttpHandler

    public void ProcessRequest(HttpContext context)
    {
        string action = context.Request.QueryString["action"];
        string[] args = context.Request.QueryString["args"].Split("|");

        MyController controller = new MyController();  // whatever your controller class is
        MethodInfo mi = controller.GetType().GetMethod(action);

        if (mi != null)
        {
            context.Response.ContentType = "text/html"
            context.Response.Write(mi.Invoke(controller, args));
        }
    }

}


问:
Can I use jQuery Mobile if I am developing a native app?
I am new to jQuery and mobile apps development. I know the features of jQuery Mobile. I want to know where and why to use it. Can I use jQuery Mobile if I am developing a native app?</p>

答:
You CAN. Your whole native application could be a single web browser screen (on iOS that would be a UIWebView) loading up local html and js content, and for that you absolutely can use any js library you like, including jQuery Mobile, JQ Touch, Sencha, or whatever.

SHOULD you? Maybe. Depends on whether you have the time and inclination to learn the native stuff for the platform you're developing for. Wrapping a web application has its benefits--it's how things like PhoneGap and Titanium work. You'll never build something that's as nice or fast or integrated as a native app, but it's quicker to develop.


问:
Where is the M in MVC?
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).

答: Model is the code that has connection to V and C in the frontend, and to the persistent storage (can be anything from files to SQL/NoSQL databases) in the backend. It is not only the code that loads from db and stores to db (which is one of misunderstandings of the model), it is the code that actually does all the "domain" work - selects, filter, alters, computes, decides over the data. Includes all the non-UI logic of the application.</p>

Title: Where is the M in MVC?


答:
Yea, both the model in the code and database are the "Model".

The model has to do with what your application "IS", and the controller is what it "does".  Any code dealing with direct persistence to the database is considered the Model.

Note: MVC is a pattern, so don't over-think it.  It's easy to get all super into doing MVC the right way, but at the end of the day, it's just a mindset!  It means keep your business logic out of the database and UI - that's it.  Before MVC, people would put business logic all up in their webpages when it should be on the server, or they would have a bunch of scripts firing in the database doing business logic right along with the persistence code.  MVC was brought about to get people to start thinking in a way that helps make their code reusable, so don't get caught up in the details too much.

Title: Where is the M in MVC?

Body:
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).


答:
Actually, I would worry more about communication than UI. From UI point of view Silverlight is perfect, but from communication point of view...

If it's peer-to-peer, than you can have problems with NAT, firewall etc, Silverlight will require OutOfBrowser expanded security mode to create TCP sockets.

If it's through Server, than you need commonication technology that supports sending notification to clients (callbacks), and WCF + Silverlight is not very simple in such scenario.

Title: I want to write a 2-player web-based board game. Which framework should I use?

Body:
I am a C# software developer.  I was recently approached by a client to develop a multiplayer board game (max 4 players).  I fiddled around with WCF, WPF and EF 4.1 to get something going but I keep running into small stumbling blocks.  It certainly does appear that integrating all these technologies into one solution is problematic.

I do not have extensive experience in WPF/WCF but I find the concepts easy to grasp.  It's just that I keep running into little problems which are huge stumbling blocks.

My thoughts were to first create a WCF service to manage the boards and rules.  I would then turn to the UI (possibly Silverlight/WPF).

I am actually at the point where I think I should try a framework or even venture to PHP/Ruby/Python.

The requirements are simple:

Web based

Turn based

Board game

Database backend

As a C# developer (possibly a poor one), what would you suggest?


答:
The most important bit of information in the commit log is the 'why', not the 'what'.

A short summary of the changes can be useful, but usually you can get that information from the diff itself. It's not a huge problem if that's missing.

Looking back at a commit log, you'll want to know why that change was done. A bug ID can go a long way in answering that question. Sometimes more explanations are required.
For example, if you fix a probem on bad input explain what input caused the problem, and if it's not trivial also how it could occur.

Title: What should I put in comments while commiting to the Source Control?

Body:
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?


答:
Yes you are right.

(Model View Controller)

An architecture for building applications that separate the data (model) from the user interface (view) and the processing (controller).

In practice, MVC views and controllers are often combined into a single object because they are closely related. According to MSDN

The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.

Check this diagram:

For example, the controller code validates a request for data and causes it to be returned in a view. View-controller objects are tied to only one model; however, a model can have many view-controller objects associated with it.

Title: Where is the M in MVC?


答:
We are using assembla on our project. We build the cardwall with all featuers/bugs that need to be done and when commiting we just refer to this ticket

For example:

```<code>see #243
 - Grid listed all users with an income more then 1000$ but not the ones that have
   exactly 1000. Added a >= in the file xy.cs on the line xyz
</code>```

This way you we are able to pinpoint the changes quicker and find some mistakes easier

Body:
We are using assembla on our project. We build the cardwall with all featuers/bugs that need to be done and when commiting we just refer to this ticket

For example:

see #243
 - Grid listed all users with an income more then 1000$ but not the ones that have
   exactly 1000. Added a >= in the file xy.cs on the line xyz

This way you we are able to pinpoint the changes quicker and find some mistakes easier


问:
Documentation with images - what is the most git-friendly approach?
When documenting software I traditionally write a plain text file (like a README.txt) which works well, but unfortunately cannot contain images like HTML can.  Unfortunately images must be stored as separate files with a normal HTML document (using href=".../foo.png">) which give unnecessary clutter.

The "Save a single web-page" in Internet Explorer use MIME HTML (MHTML) to save all resources within a single file.  The requirement of having to use a browser to read it, is not a impediment these days.  Apparently Opera and Word support editing these documents directly.

We use git for our source code, hence the differences as seen by git between two edits of the same documents should not be large to avoid unnecessary disk usage and unusable diff's when looking at the document outside the MTHML editor.

What is the best mainstream HTML editor for producing git-friendly MHTML files?

答: Why not try the approach with Markdown - that way, you can have HTML with images, and the "original" will still be in plain textual format, easy for diff.</p>


答:
To my understanding, MVC is just the description of the architectural pattern of your client application. The picture here in Wikipedia just shows this:

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Of course, when you have parts of you application implemented in "stored procedures", then those database code may also be part of the model, or even of the controller (depending what the code does). But if that's not the case, then the database is clearly "outside of MVC", just as you stated it.

Title: Where is the M in MVC?


问:
C++ XML Parsing: Suggestions on Approach for Parsing and Storing data
I am looking into developing a C++ application to parse xml (using the rapidxml framework), and I would like some advice on how to approach this.

The file I want to parse is a XML game file that defines a set of addons for a starship ('outfits'), which have several attributes in common (like name and cost), but also fall into various categories.

For example:
Fixed weapons: range, rate of fire

Turret weapons, range, rate of fire, turret slew speed

Afterburners: acceleration modifier, fuel burn speed

etc etc etc

There are at least 5 classifications of outfits (and say 3 or 4 outfits that fall into each category), and some, like the weapons, have a few attributes in common with each other, but not with other categories like afterburners.

I want to write parsing code to handle each type of object and store its data in objects. I also want to minimize how much code I have to retype (i.e. make use of good OOP style so I can add new categories or tweak existing ones in the future).

What is the best way to approach this? I have already started the program, but I would like to have some input on the best approach.

Since this is a really broad question, I will give you some of my thoughts/specific questions so you can see what I am looking for:

Should I have a basic class called 'outfit' and use inheritance to customize the parsing for each specific category (i.e. 'fixed-weapons')? Should I have multiple levels of inheritance for similar categories (i.e. 'weapons'). How can I minimize code retyping so I only have to write the specific routines for each category?

Where should I handle the errors: in 'outfit', or in the derived classes? How much error handling do I need?

How can I easily access these objects later? Should I make a list-object with a vector containing each object? How can I access each object by name?

Any input is appreciated; you don't have to give a complete and comprehensive rundown on how to do this (though that would be nice :P).

答: I would use CodeSynthesis to parse XML into an object (this can be templated to handle any CodeSynthesis classes) and then use these objects to create the actual game related objects with a builder class.  These CodeSynthesis classes can then easily be serialsied back out to XML as and when required.</p>


答:
Taking a very simplistic and idealistic view.

The Model is generally seen as a model of the domain (roughly, the business), not as a model of the data. These may look similar, but they are not completely tied to one another.

The View should be a model of the application front end and the Controller should be a model of the flow from one view to another.

Business logic should be entirely encapsulated in the Model, whether it be in the database or code. Although some business logic may be repeated in the View or Controller, for various reasons, it should be possible (and safe) to remove those two components completely and put a different front-end in its place.

Title: Where is the M in MVC?


问:
Java void methods implicitly returning this
there are a couple of discussion on SO about setter methods returning "this" type. And looks like java 7 had the proposal of void methods returning this.
But this proposal could not make it to java 7 features.
I could not find if this proposal is moved on to java 8 or future or have been completely discarded. Is it?

Ref link - https://stackoverflow.com/questions/31584/design-java-and-returning-self-reference-in-setter-methods

答:
I can't seem to find any sources of that, but I believe this feature was dropped completely. There are numerous reasons I can think of:

performance - each void method now has an extra return opcode and every place where this method is called needs implicit pop unless it actually uses method chaining

backward compatibility - compiling against this feature suddenly makes the code backward incompatible because the contract of every void method has changed

Of course this can also be implemented by the compiler (calling method on void? You probably meant this, let me add this implicitly), don't know what are the disadvantages of this approach.

OwnerDisplayName: Tarun

OwnerDisplayName: Tomasz Nurkiewicz


答:
I don't believe this was ever formally proposed for the 2009 incarnation of Project COIN.  This page purports to list all of the proposals, and I can't see one that corresponds.

If it wasn't proposed, it wouldn't have been considered.

Title: Java void methods implicitly returning this

Body:
there are a couple of discussion on SO about setter methods returning "this" type. And looks like java 7 had the proposal of void methods returning this.
But this proposal could not make it to java 7 features.
I could not find if this proposal is moved on to java 8 or future or have been completely discarded. Is it?

Ref link - https://stackoverflow.com/questions/31584/design-java-and-returning-self-reference-in-setter-methods

OwnerDisplayName: Stephen C


答:
You don't have to know much about how a car functions to drive it but you'll almost certainly, at best, only be a relatively average driver. The more you know about cars the better driver you can be. To be an elite driver, you will know as much as possible about every detail of your car, its engine, even your physiology and the ergo-dynamics of the cockpit. It then doesn't much matter what car you drive, you'll be able to quickly assess its capabilities and drive it effectively.

Or, simply, as with anything, the more you know, the better at that profession you will be.


答:
```<code>But then, what is in the database -- is that not also the model?
</code>```

No it is not.  "The model manages the behaviour and data of the application domain".  Often, the Model hooks into a database yes, but in no way is that a requirement.  The model is a new layer between your application and the database.  The backend could be a set of Mock objects, XML, or anything else that supports data persistence.

By decoupling the layers you give yourself much greater flexibility to use better unit testing practices, make the code more manageable (E.G. SQL gets replaced by Oracle) amongst other benefits.

The same goes with the controller.  MVC defines the controller as a middle man between the two layers.  There is no "business layer" defined in MVC.  Rather, you add your own.  MVC does not encapsulate all layers required to build most applications.  It's just a general guideline for the basic structure.

These separations are key to allowing inversion of control to function.

Title: Where is the M in MVC?

Body:
But then, what is in the database -- is that not also the model?

No it is not.  "The model manages the behaviour and data of the application domain".  Often, the Model hooks into a database yes, but in no way is that a requirement.  The model is a new layer between your application and the database.  The backend could be a set of Mock objects, XML, or anything else that supports data persistence.

By decoupling the layers you give yourself much greater flexibility to use better unit testing practices, make the code more manageable (E.G. SQL gets replaced by Oracle) amongst other benefits.

The same goes with the controller.  MVC defines the controller as a middle man between the two layers.  There is no "business layer" defined in MVC.  Rather, you add your own.  MVC does not encapsulate all layers required to build most applications.  It's just a general guideline for the basic structure.

These separations are key to allowing inversion of control to function.


答:
Trygve Reenskaug wrote the initial papers describing the MVC pattern back in 1978. The Model in his description was the object model representing real world objects, phenomena, and concepts. In your scenario of a database-backed application, the model is a projection of your data. To put it simply, the model is the classes and their relationships that your application is concerned with.

In practice, there are usually two models used in MVC, the Domain Model (what's mapping to your database) and the Application Model (also called the View Model in today's terminology). The Application Model is a projection of the Domain Model that also contains view specific data for rendering the view. This approach is called MMVC. The controller directly interacts with the domain model and presents an application model to the view. In the MVVM pattern the Application Model and Controller are combined.

Title: Where is the M in MVC?


答:
I'd store images and text separately in source control; this way, even though your images are binary blobs (and thus not handled efficiently), you won't have a lot of small changes on binary files, provided you don't change the images themselves much.

Choose a documentation source format that fits your needs - HTML, Markdown, DocBook, LaTeX, etc. - and store only the sources (and the images you need to include) in source control. Then, just like with the code itself, you set up a build system, which allows anyone to build documentation in a consumable format (probably several of them, e.g. multi-file HTML, MHTML, PDF) from the sources.

Title: Documentation with images - what is the most git-friendly approach?

Body:
When documenting software I traditionally write a plain text file (like a README.txt) which works well, but unfortunately cannot contain images like HTML can.  Unfortunately images must be stored as separate files with a normal HTML document (using href=".../foo.png">) which give unnecessary clutter.

The "Save a single web-page" in Internet Explorer use MIME HTML (MHTML) to save all resources within a single file.  The requirement of having to use a browser to read it, is not a impediment these days.  Apparently Opera and Word support editing these documents directly.

We use git for our source code, hence the differences as seen by git between two edits of the same documents should not be large to avoid unnecessary disk usage and unusable diff's when looking at the document outside the MTHML editor.

What is the best mainstream HTML editor for producing git-friendly MHTML files?


答:
I did some research into the problems of novice programmers in the 80s. Based on my experience with novice programmers today, not much has changed. Novices don't have a useful mental model of what computers actually do. They resort to magic incantations because the machine itself is magical.

Programming requires breaking naturally simple tasks into unnaturally small steps. Since novices don't deal with such fine granularity in daily life, it's hard for them to figure out what the small steps should be, especially when it's not clear what small steps the machine makes available. But even if they do manage to figure that out, they are then confronted with the stilted syntax and limited semantics of a programming language (an unnatural language masquerading as a quasi-natural one) that controls the mystery machine by remote control.

Since they can't make the connection between a logical solution to the problem and the functionality of the machine, they focus on satisfying the demands of the language. The first goal is to write something - anything - that compiles. The second is to tweak that program - whatever it actually does - to keep it from crashing. Then, if they have the time, the energy, and the interest, they try to get the program to produce results that resemble what the problem requires. Along the way, they may accidentally produce well-written code.

In all likelihood, novices who do learn to program succeed because they have inferred a useful mental model of the computer, not because they've been intentionally given one and internalized it.

Title: How can I deal with the cargo-cult programming attitude?

Body:
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?


问:
What's the idiomatic name for a throwaway variable?
Velocity Template Language's set directive requires a variable on the left hand side. This doesn't work.

```<code>#set ( $entries.add("d") )
</code>```

Even though I have no use for the return value of add("d"), I have to assign it to a variable.

```<code>#set ( $x = $entries.add("d") )
</code>```

I want to communicate that the variable is necessary, but I have no intention of using it later. Is there a convention for naming variables that only exist to appease the compiler?

答: I tend to use dummy for this kind of situation (a variable that I must have though I don't need to use).


答:
dummy, temp, trash, black_hole, garbage ... any one of these tells me I won't be using them for anything.

If I do use if for something, I always rename the variable though.

Title: What's the idiomatic name for a throwaway variable?

Body:
Velocity Template Language's set directive requires a variable on the left hand side. This doesn't work.

```<code>#set ( $entries.add("d") )
</code>```

Even though I have no use for the return value of add("d"), I have to assign it to a variable.

```<code>#set ( $x = $entries.add("d") )
</code>```

I want to communicate that the variable is necessary, but I have no intention of using it later. Is there a convention for naming variables that only exist to appease the compiler?


答: You should check and see if your language has a name specifically for this use - Python has _ that you should use for variables you intend to throw away.


答: I would give it a reasonable name and add a comment explaining that you are only assigning it to appease the compiler. I have seen cases where someone has used a variable name like unused and another developer has subsequently used that variable by that name and made an ugly mess of the code.


答:
You seem to be assuming that MHTML is the only way of embedding images into HTML. On the basis that that is an assumption rather than MHTML being an absolute requirement, I'd suggest using HTML and data URIs. That allows you to edit the text and get diffs using a standard text editor; if you're going to be editing the images a lot you'll probably want a text editor which supports base-64 en/decoding. Notepad++ has a standard plugin to do this, and I'm sure other editors targeted at programmers will too.

I should note that I've never used this approach for documentation, but I have used it for app_offline.htm pages.


问:
How should I handle logging when I create libraries for others?
All. I am creating some libraries for other teams in my company. They all have different logging mechanisms. I want to provide trace information of what my libraries are doing. What should I to achieve this? Thanks</p>

答:
Use the built in Trace mechanism and document the fact.

This way, all they need to do is configure tracing and they can log.


问:
How is the development of languages like Python and Perl funded?
The title pretty much gives you the gist of the question, but allow me elaborate a bit nevertheless. Apart from Google's involvement on Python, and Activestate's on Perl development (Strawberry AFAIK doesn't make any money on its own product) I'm interested in what are the major sources of funding of such.

Are there any texts that cover this? I tried searching, but found nothing apart from the "history of" and "it's opensource, everyone gives in" ...

答:
Language don't need funding, but they get a lot more love and attention if someone pays developers to work on them. What happens is that companies that rely on the languages hire developers who work on the languages to work on them either full or part time.

Guido works for Google -- I would not be surprised to find out that they pay him a salary to be the Python BDFL. Larry worked for O'Reily for a while officially working on writing Perl books, but large parts of that was making sure there was a Perl to write books about.


问:
How important is learning Algorithms for high level language programmers

Possible Duplicate:

  How important is studying algorithms and theory is to becoming a great programmer?

Today I learned the fast sort Algorithm. I doubt I will ever implement my own version though as C# has its own built in Sort method for lists and arrays.

How important is learning Algorithms for high level language programmers? In my example I gained no benifit from knowing the Algorithm but perhaps my example was too trivial to be accurate?

答:
Every program is an algorithm. Learning algorithms is about learning the more generic patterns, and the concepts involved. I never need a sort algorithm by itself, but I need a sort plus a tree plus a unique set of steps to solve a problem. I end up with an algorithm that is unique to this problem.

If I don't know about designing algorithms, how will I solve my problem? You probably won't write a new sort, but the classic quote "Data structures + algorithms = program" is true for every program. You have to know which algorithm to use where, and how to build your own.

I leave aside completely the fact that algorithms are useless in a data vacuum.


答:
You have plenty of good answers already, however I thought I'd toss one that's more directly related to velocity.

What is the add method returning?  If it's null you can simply tell velocity to quietly reference it:

```<code>$!entries.add("d")
</code>```

However if you are replacing a value, and it returns the old value (like Map.put does), then you would need to set it to a dummy variable of some sort, if it's a void method, then you shouldn't need the variable at all.

If you're adamant about not using a new variable you could do the following:

```<code>#if($entries.add("d")) #end
</code>```

If you're using it often enough I'd create a macro for it, then use it throughout your templates.  I don't see how useful that might be though, but at least you'd only need to comment it once...

Body:
You have plenty of good answers already, however I thought I'd toss one that's more directly related to velocity.

What is the add method returning?  If it's null you can simply tell velocity to quietly reference it:

$!entries.add("d")

However if you are replacing a value, and it returns the old value (like Map.put does), then you would need to set it to a dummy variable of some sort, if it's a void method, then you shouldn't need the variable at all.

If you're adamant about not using a new variable you could do the following:

#if($entries.add("d")) #end

If you're using it often enough I'd create a macro for it, then use it throughout your templates.  I don't see how useful that might be though, but at least you'd only need to comment it once...


答:
Algorithm knowledge is absolutely essential for programmers for the following reasons:

Programming is everything about handling large amounts of details. Details that are all linked together to a consistent system. Algorithms are just well known patterns of details, where solutions are known. 99% of the cases the details are not structured like those well known patterns expect, and the algorithms need to be customised to the particular situation -- it's just not possible to write any significant software without algorithm knowledge.

Data structures are another aspect of the same problem. Computer memory storage lets us store information. But deciding correct representation in the computer memory for that information in every state during the algorithm execution is significant problem in itself. If there are problems with learning algorithms, then learning data structures is simpler way to learn the same thing.

In the end, it's all about bits in the computer memory. It's either 0 or 1. There are sequences of bits like 010, and then those are then boxed inside data types. During the lifetime of the data, the value of the bits will change, and the system moves from one state to another repeatedly, and finally a normal form - the result of the program is reached, and execution stops until it is again activated by an external event.

These execution sequences in the program from activation of the execution to the normal form can become very complex. Handling this complexity together with data changes is what algorithms are all about.


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
I'm in agreement with frozenkoi, however, for C# anyways, I thought it would help to follow the syntax of the TryParse methods.

if(FileExists(file) && TryOpenFile(file, out contents))
    DoSomething(contents);
else
    DefaultAction();
```

<pre class="lang-cs prettyprint-override"><code>bool TryOpenFile(object file, out object contents)
{
    try{
        contents = OpenFile(file);
    }
    catch{
        //something bad happened, computer probably exploded
        return false;
    }
    return true;
}
</code>```

Title: Elegant ways to handle if(if else) else

Body:
I'm in agreement with frozenkoi, however, for C# anyways, I thought it would help to follow the syntax of the TryParse methods.

if(FileExists(file) && TryOpenFile(file, out contents))
    DoSomething(contents);
else
    DefaultAction();

bool TryOpenFile(object file, out object contents)
{
    try{
        contents = OpenFile(file);
    }
    catch{
        //something bad happened, computer probably exploded
        return false;
    }
    return true;
}


答:
There are dozens of questions on Programmers.SE of the form "Do I need to know X to be a successful programmer?". Programming is a huge arena with thousands of different kinds of jobs, so no matter what 'X' is, the answer is 'No', because you can find some subset of programming jobs that doesn't need 'X'.

Unfortunately, what usually goes unsaid is that each time you decide to 'just get by' and blowing off some subject, you are  implicitly making choices about the sorts of programming jobs you are going to take in the future. None of us can know everything, so these choices have to be made, but they should be made with some thought for the future of your career, not just to avoid some current inconvenience or effort.

Yes, there are lots of programming jobs where a formal knowledge of algorithms would go to waste. The question is: Are those the sorts of jobs you want to be working at ten years from now? If not, you should now begin laying the groundwork to qualify for other jobs in the future.

Body:
Possible Duplicate:

  How important is studying algorithms and theory is to becoming a great programmer?

Today I learned the fast sort Algorithm. I doubt I will ever implement my own version though as C# has its own built in Sort method for lists and arrays.

How important is learning Algorithms for high level language programmers? In my example I gained no benifit from knowing the Algorithm but perhaps my example was too trivial to be accurate?


答:
I think you should not be misled by the fact that you want to program in a high-level language. A high-level language gives you lots of abstractions (data types, control structures, memory management, standard libraries, etc) that make certain tasks easier for you.

As a result, a task that once seemed very complex (e.g. sending an email through smtp) can now be achieved by performing a few calls to some library functions. What is the consequence of this? That it is possible to construct applications that are much more complex than before.

So, at the end of the day you will still have to do with very complex software projects because high level languages have only taken the complexity of software to a different level. What I mean is that, say, implementing a business application in C#, Java or Scala can be as complex as (or even more complex than) implementing a device driver in C / assembly.

So, IMO, high-level programming languages will not protect you from having to deal with real algorithmic or architectural problems: they have made specific programming tasks easier, but they haven't made programming less difficult or challenging in general.


答: I would actually suggest using the newer TraceSource class, as recommended by the BCL Team during early .NET 2.0 development.  This adds some additional bells and whistles like the ability to name sources independently of one another and handle configuration through app.config files.</p>

Title: How should I handle logging when I create libraries for others?

Body: All. I am creating some libraries for other teams in my company. They all have different logging mechanisms. I want to provide trace information of what my libraries are doing. What should I to achieve this? Thanks</p>

ContentLicense: CC BY-SA 4.0


答: Built-in language features and library functions, like the sort function are  abstractions.  And when one of those abstractions leaks, as they invariably do, you will not know what hit you, if you don't understand complexity of algorithms. </p>


问:
Why don't more companies hire remotely?
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?

答:
I worked remotely for 1.5 years and loved it. I set up an office in my home, woke up in the morning and didn't have to drive to work and got to eat lunch with my family. This saved us a lot of money. Because of that I was in a sense earning more than I am currently. Likewise, I ended up working more hours and getting more done because I wasn't spending five hours a week driving and then getting settled into my office and I was more likely to work late on my projects after the family went to bed.

I will admit that there were some communication challenges.

If I called my team lead on the phone he was not always at his desk. I therefore didn't know if he was there at all, in a meeting, etc. I'd leave a message and he may not have returned my call for three hours which sometimes kept me from moving forward.

Thankfully I already knew their business well to allow me to run on my own but there were times where I needed to meet with my Team Lead to discuss specifications. It is difficult to draw up a blue print on paper over the phone.

I am self motivated but other remote developers were not. We had no guarantee that they were spending eight hours working on their tasks.

Sometimes remote developers were not in sync with the rest of the project plan so sometimes there were unnecessary iterations to get them on track.

I say all of that to say this: These issues aren't any different than working face to face. Every one of the listed issues is found in the local work place and it is too subjective to say it is easier in the work place than remotely. All points above occurred in the same manner whether at work or outside of it.

Take for example problem one. In the office I may have sat five cubicles away from my Team Lead. If I had a question I would've sat up from my desk and walked to his cube. It takes less time to pick up a phone that's next to me to call. Likewise, if he was in a meeting while I was there, I would still have to wait for him to get back from his meeting or whatever else.

Problem two is a little more challenging to justify but with Skype, Collaboration Software, etc, this is definitely doable.

Three and four are problems in communication and understanding in general. These are operational issues that exist locally or remotely and in each environment they require innovative forms of leadership.

I would add a couple of things to this mix and that is cost. If a techie is in the office they will be using electricity to run their computer and cubical lights, run water for drinking or flushing the toilet, they will chit-chat with co-workers, wear down carpet, spread illness, etc, etc. If five developers are not at work, it would be interesting to determine the cost savings in areas like this.

Title: Why don't more companies hire remotely?


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答:
Something I have found to be very helpful for the people in my class is writing a small project on their, on a subject they can choose themselves.

When I started programming, it was hard for me as well, and I did copy a lot in class. Then at home, I started making little games, as I want to become a games programmer, and I found them to be much easier to make. Even though they were much harder then the stuff we saw in class. Just because it interested me.

A few other people in my class went from 40-50% on their exams to 90-100%, because they did the exact same thing.


答:
Do not underestimate the information bandwidth of being physically together with your co-workers!

Most non-trivial projects need to be parallelized to ever get done.  This mean more than just you working on the project with which you will need to communicate intensely to save time and effort for your employer.   Double so, if you are the only one never there which your co-workers must make an extra effort to keep you up to date.

Title: Why don't more companies hire remotely?

Body:
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?


问:
A Project's Initial Commit to Source Control
I'm probably over-thinking this and it might not matter in the scope of things, but I'm wondering how people build up initial versions of their projects in source control? I'm talking about when you start with nothing but an idea, so no forking an existing project or anything.

When do you do your commits before having an official or even unofficial version?

At what point do you start branching for features, or do you this right away?

I'm so used to working with existing code bases that I'm not really sure I know if there's a "best" way to build up a project history.

答:
I typically just start using a local mercurial repository and committing to default. If it grows legs, I'll push it over to the central repository and setup continuous integration and such.

Branching is much more of a tactical decision. If the development is linear, I'll often just stick with default until I need to have concurrent versions out there -- like something a bit more fixed for QA or integration testing. At that point I'll add the long running development and release branches.

If the the project requires a bit more experimental development, I'll use named branches to contain the experiments from the get go. Merges are fun and easy in HG so you might as well use them.


答:
You don't need a database for MVC. If your model happens to talk to the database, then great. It could also persist itself to a flat file, or not persist itself at all.

The model is where data is stored in memory in your application. You will also want to use the model to do calculations and validations on its data. For example, you have a FinancePayment model, with properties such as interest rate, term, and principle. You might add a getMonthlyPayment() method to your model to calculate the monthly payment. You wouldn't want to do that in the controller or view.

The view should be reasonably dumb, either having no logic at all, or using only simple data binding (see Passive View and Supervising Controller patterns on Martin Fowler's site ). The view raises events when the user does stuff, like clicking a button.

The controller is responsible for handling events (run some code when user clicks save button), and for setting model properties, and telling the model to load and save itself (if using persistence). The controller should not be doing calculations on the model's data. However, in the controller, you might do some calculations on behalf of the view, such as "if model.profit() < 0 then widget.colour = 'red'"

You should be able to switch to a command line version of your application without changing the models, and without losing the functionality of the models.

a. You should probably be able to switch to a mobile version of your application (as opposed to a desktop version) by only switching the views (and not the controllers or models). You should be able to unit-test your models and controllers without a GUI testing framework.

Title: Where is the M in MVC?


问:
Instantiating a class implementing an interface
I have an interface called Cell. In the start of the code, I read input data from which I can come to know the implementing class (not as a class object but I can know for example the string). And after that I need to call the constructor for the implementing class to initialize an object.

What would be the best way to implement that. The first thing in my mind is to do something like this (Cell is an interface, Sphere and Rectangle implements Cell. I can set a boolean flag called sphere after reading the input data):

```<code>Cell startcell;
if (sphere)
    startcell = new Sphere(0);
else
    startcell = new Rectangle(0);
</code>```

But is this good design?

答:
Looks like Factory pattern, which is quite "endorsed" by design gurus, so to speak.
See bottom of that Wikipedia pages for existing creation patterns for OOP languages, like Java.</p>

OwnerDisplayName: Captain Jack sparrow

OwnerDisplayName: Victor Sorokin


答:
When do you do your commits before having an official or even unofficial version?

Follow the philosophy of committing as often as possible.  I use Subversion most of the time.  As soon as I have any code that I wouldn't want to lose, and I would want to revert to if I screw something up, I do my first commit.

At what point do you start branching for features, or do you this right away?

I wouldn't do this until after the first release, or if there are multiple developers that need to work on the same areas of the codebase for different purposes that might not be released at the same time.

Title: A Project's Initial Commit to Source Control

Body:
I'm probably over-thinking this and it might not matter in the scope of things, but I'm wondering how people build up initial versions of their projects in source control? I'm talking about when you start with nothing but an idea, so no forking an existing project or anything.

When do you do your commits before having an official or even unofficial version?

At what point do you start branching for features, or do you this right away?

I'm so used to working with existing code bases that I'm not really sure I know if there's a "best" way to build up a project history.


答:
The if/else implementation is not very scalable - as soon as you add a Cube, you have to add another if condition.  It's not really a design pattern, but Java can handle this with reflection.  You can read the class name from some config and instantiate it and verify that it implements the appropriate interface.  Just a side note, the Spring framework can do this for you too.</p>

```<code> // className is read from config, etc
 Class instantation = Class.forName(className);

 if (!Cell.class.isAssignableFrom(instantation))
     throw new Exception("Not a Cell!");

 Cell cell = (Cell) instantion.newInstance();
</code>```

Title: Instantiating a class implementing an interface

Body:
I have an interface called Cell. In the start of the code, I read input data from which I can come to know the implementing class (not as a class object but I can know for example the string). And after that I need to call the constructor for the implementing class to initialize an object.

What would be the best way to implement that. The first thing in my mind is to do something like this (Cell is an interface, Sphere and Rectangle implements Cell. I can set a boolean flag called sphere after reading the input data):

```<code>Cell startcell;
if (sphere)
    startcell = new Sphere(0);
else
    startcell = new Rectangle(0);
</code>```

But is this good design?

Body:
The if/else implementation is not very scalable - as soon as you add a Cube, you have to add another if condition.  It's not really a design pattern, but Java can handle this with reflection.  You can read the class name from some config and instantiate it and verify that it implements the appropriate interface.  Just a side note, the Spring framework can do this for you too.

 // className is read from config, etc
 Class instantation = Class.forName(className);

 if (!Cell.class.isAssignableFrom(instantation))
     throw new Exception("Not a Cell!");

 Cell cell = (Cell) instantion.newInstance();


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

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

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

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

His problem is with the first line code:

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

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

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

答: You would only need to put it in a constant if it has a complex derivation, or if it's repeated often. Else, a literal is fine. Putting everything in a constant is total overkill.</p>


答:
The order in the combo box could change.  What if you add another option like "Create Special Vendor..." before  your "Create New Vender..."

The advantage of using a constant is if there are many methods that depend on the order of the combo box, you only have to change the constant and not all the methods if this does change.

Using a constant is also more readable than a literal.

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

Most compiled languages will substitute the constant at compile time, so there is no performance penalty.

Title: Is this a correct situation to use a constant?

Body:
So my professor was giving back some feedback on a project I've been working on. He docked a few marks for this code:

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

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

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

His problem is with the first line code:

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

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

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

Body:
The order in the combo box could change.  What if you add another option like "Create Special Vendor..." before  your "Create New Vender..."

The advantage of using a constant is if there are many methods that depend on the order of the combo box, you only have to change the constant and not all the methods if this does change.

Using a constant is also more readable than a literal.

if (comboVendor.SelectedIndex == NewVendorIndex)

Most compiled languages will substitute the constant at compile time, so there is no performance penalty.


答:
That is the total preference of your professor. Typically, you only use a constant if the literal will be used multiple times, you want to make it obvious to the reader what the purpose of the line is, or your literal will possibly be changed in the future, and you only want to change it in one place. However, for this semester, the professor is boss, so I would do it from now on in that class.

Good training for the corporate world? Quite Possibly.


答: I would have replaced the 0 with a constant to make the meaning clear, such as NewVendorIndex. You never know if your order will change.


答:
He is not wrong for stressing the value of using constants and you are not wrong in using literals. Unless he had stressed that this is the expected coding style, you should not lose marks for using literals since they are not harmful. I have seen literals used all over the place so many times in commercial code.

His point is good though. This may be his way to make you aware of the benefits of constants:

1-They protect your code to some extent from accidental tampering

2-As @DeadMG says in his answer, if the same literal value is used in many places it may appear with a different value by mistake - So constants preserve consistency.

3-Constants preserve type, so you don't have to use something like 0F to mean zero.

4-For ease of reading, COBOL uses ZERO as a reserved word for the value zero (but also allows you to use the literal zero) - So, giving a value a name is sometimes helpful, for example: (Source: ms-Constants

```<code>class CalendarCalc
{
    const int months = 12;
    const int weeks = 52; //This is not the best way to initialize weeks see comment
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}
</code>```

or as in your case (as shown in @Michael Krussel answer)

Body:
He is not wrong for stressing the value of using constants and you are not wrong in using literals. Unless he had stressed that this is the expected coding style, you should not lose marks for using literals since they are not harmful. I have seen literals used all over the place so many times in commercial code.

His point is good though. This may be his way to make you aware of the benefits of constants:

1-They protect your code to some extent from accidental tampering

2-As @DeadMG says in his answer, if the same literal value is used in many places it may appear with a different value by mistake - So constants preserve consistency.

3-Constants preserve type, so you don't have to use something like 0F to mean zero.

4-For ease of reading, COBOL uses ZERO as a reserved word for the value zero (but also allows you to use the literal zero) - So, giving a value a name is sometimes helpful, for example: (Source: ms-Constants

class CalendarCalc
{
    const int months = 12;
    const int weeks = 52; //This is not the best way to initialize weeks see comment
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

or as in your case (as shown in @Michael Krussel answer)


答:
It is very simple actually, "Model" represents the abstraction for the data interface. That is why:

Databases are regarded as part of the Model, but not the model itself

The Model's data can come from databases, files, web-services or even be mocked.

Model classes in MVC, HMVC or similar frameworks should store queries (see "fat model, skinny controller" principle [1][2][3])

And —if I'm correct— that's why when someone refers to models outside MVC context, that someone most likely refers to the structure of the data (i.e. schema).

Title: Where is the M in MVC?

Body:
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).


答:
This situation you describe is a judgement call, personally I wouldn't use one if its only used once and is already readable.

The real answer though is that he picked this off to teach you a lesson.

Don't forget that he is a professor, his job is to teach you coding and best practices.

I'd say he is doing a pretty good job actually.

Sure he might come off a bit absolute but I'm certain you'll think again before using magic numbers.

Also he got under your skin enough for you to join an online community about programmers just to find out what is considered a best practice in this situation.

Hats off to your professor.


问:
What should I put in comments while commiting to the Source Control?
I am a lone developer and maintain a SVN server for source control. So far, I haven't followed anything specific while committing my changes.

I was just reviewing my previous commits, and couldn't make any sense of my comments.

What do you put in comments while committing your checkins?

答:
I tend to write a concise form of what I'm committing; if it's for a specific task, I'll include the task number in the message.  Things like:

```<code>Changed foobar module to account for the new baz; created quux pages and data objects.
</code>```

What not to do is write some nonsense like "Oops" or "Added comments" (both of which I have seen added in the commit logs by a co-worker), or worst of all do something like I saw the other day - A single file was checked in, with the commit message "Comment" (exact quote).  What was added, you may ask?  Something to the effect of:

```<code>if (z == true) {
    x = y; // x is being overridden here... <--- added in commit
}
</code>```

And no, we are not measured by the number of commits.

Body:
I tend to write a concise form of what I'm committing; if it's for a specific task, I'll include the task number in the message.  Things like:

Changed foobar module to account for the new baz; created quux pages and data objects.

What not to do is write some nonsense like "Oops" or "Added comments" (both of which I have seen added in the commit logs by a co-worker), or worst of all do something like I saw the other day - A single file was checked in, with the commit message "Comment" (exact quote).  What was added, you may ask?  Something to the effect of:

if (z == true) {
    x = y; // x is being overridden here... <--- added in commit
}

And no, we are not measured by the number of commits.


答:
A s  a  s e l f - t a u g h t   programmer I believe animation to be the most challenging in terms of knowing what the code is doing. When a program contains algorithms and mathematical transformations performing abstract manipulations, the only way to understand what the math is doing at any given point (unless you're a genius) requires understanding the execution of code itself.

Correct me if my naive idea is incorrect. What you want to do is not prevent your students from using "design patterns", but to find a way to ensure they understand what they are CnP's? Then challenge your students to manipulate an animation. In order to tweak the output in an animation its necessary understand what is happening at each step. For your stated concern, I imagine a well conceived animation project will manifest in obvious ways when a student "gets it"--when they have realized a transformation you didn't expect or tweaked certain related, interdependant variables.

Without knowing the pedagogical limits and goals you are working under, I can't say animation is the complete answer. A whole curriculum of animations outside of animation profession is, I should hazard to guess, out of the question. A few projects may none the less result in something artful and wonderful, which isn't bad.

On another note, I read a newspaper article (yes, paper!) about a high school-level Coding Olympics--wot-wot--competition for pre-college programmers. The description of their challenges was the clearest articulation of pure coding I can recall having read. The competitors are judged against each other and by good practice standards. For these competitions students must both plan their solution and hand code the elemental "design pattern" which the problem requires to finish within time limits. Thus, the solution to your concern regarding CnP programming is to test if the students can write the same "code chunks" they are CnP'n!

I'm sure it was in the NY Times. A quick search didn't find it. A similar example is ACM's International Collegiate Programming Contest. This contest emphasizes speedy programming: "Lightning-quick programming in team competition is a decidedly quirky skill, not exactly one many job seekers would place at the top of a résumé." Thus I would recommend abstraction from real-world problems is the answer.

Also,

HP Code Wars


答:
Follow the unit of work pattern :)

Whenever you finished a part of a feature and the code compiles then commit.

Don't worry about the commit messages until you get to release the code into the wild. When it comes to that, many projects delete all the revision history and re-initialize the repository. Then and only then does it makes sense to over-think it.

This way you get to have many pet projects and the few that get good enough get to be released.

As to when to use branches I'd say if you are alone then you might not need them. Pick one feature at a time and complete it.


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
I think that asking questions and troubleshooting is a skill that needs to be learned, and for professional developers, it's an important skill that simply isn't taught often enough.

Just as the code you write when you first start in this profession is going to be horrible compared to the code you write today, the questions you ask are going to be terrible compared to the way you ask them today.

When you start out, it's easy to be overwhelmed by all of the information that you are learning and when things aren't going to plan, it's difficult to know what information is relevant and what isn't. This is a big part of the reason why beginners can't solve the problem for themselves in the first place!


问:
Is having your own website important?
How necessary or important is it? I try to keep a running list of blogs or sites to follow, but a lot of the time I pull up someone's profile and notice there isn't anything there. Is it really important?

I understand are different levels of programming (from C/C++ system programmers to Rails and even Haskell and J) and not everyone works in a language easily worked with for web based applications. Not everything is web-centric, however with the advent of many popular and sometimes free services I don't think it's unreasonable to expect a majority of programmers to have a personal site.

答:
I say this with as much love as possible, but...

Do the world a favor, and maintain a blog or website only if you have something substantial to say.

I fancy myself a reasonably good developer, and I feel like my body of work on StackOverflow is pretty decent.  But I don't have a blog.  Why?  Because there are many smart people out there who can write blogs much better than I can.

There is enough chaff on the internet already.

Title: Is having your own website important?


答:
He's right.
You're right.
You're wrong.

He's right, conceptually, that magic numbers should be avoided.  Constants make code more readable by adding context to what the number means.  In the future when someone reads your code, they know why a particular number was used.  And if you need to change a value somewhere down the line, its far better to change it in one place rather than try to hunt down everywhere where a particular number is used.

That being said, you are right.  In this specific case, I really dont think a constant is warranted.  You are looking for the first item in the list, which is always zero.  It will never be 23.  Or -pi.  You are specifically looking for zero.  I really dont think you need to clutter the code up by making it a constant.

You are wrong, though, in assuming a constant gets carried around as a variable, 'using memory'.  A constant is there for the human and the compiler.  It tells the compiler to put that value in that spot during compilation, where you'd otherwise have put a literal number.  And even if it did carry the constant in memory, for all but the most demanding applications, the loss of efficiency wouldnt even be measurable.  Worrying about the memory use of a single integer definately falls into 'premature optimization'.


答:
To be honest, while I don't think your code is best practice, his suggestion is frankly a little grotesque.

A more common practice for a .NET combobox is to give the "Select.." item an empty value, while the actual items have meaningful values, and then do:

```<code>if (string.IsNullOrEmpty(comboVendor.SelectedValue))
</code>```

rather than

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

Body:
To be honest, while I don't think your code is best practice, his suggestion is frankly a little grotesque.

A more common practice for a .NET combobox is to give the "Select.." item an empty value, while the actual items have meaningful values, and then do:

if (string.IsNullOrEmpty(comboVendor.SelectedValue))

rather than

if (comboVendor.SelectedIndex == 0)


问:
How do you maintain a common library used by different clients?
I am part of a software deveopment team. Originally there were just 2 of us, and two applications. To ease our job we create a set of libraries, handling stuff like GUI, database access, calculation, business rules etc, so that we can reuse them in our applications without implementing them twice.

Now the team grew, 6 people and ~5 applications (and growing). The applications use the same library, which are great because we don't have to develop and maintain the same thing more than once. I and the other initial guy developed and are mostly responsible for the library, but other people have access to the code and occasionally update it to fix bugs and add improvements.

But soon we notice that the more we grow and the more people can modify the code, there is a risk that "improvements"/"bug fixes" that someone does can unintentionally break someone else's application which depends on the old behavior. On the other hand, assigning one guy to maintain the libraries and make sure modifications won't break anything is not practical because there are many applications, and possibly many improvement requests to be done, and he can't be sure of everything either.

How do teams normally manage situation like this? Perhaps by implementing rules on allowed modification? Defining behaviours that shouldn't be changed? There are a lot of libraries in the internet used by a lot of people, for example open-source/free to use libraries like Apache, Castle, etc. How do they make sure that changes won't break existing client codes?

答:
You create a public API and version it. The consumers ( the other projects ) get to follow the API and you get to unit test it thoroughly.

Also it is a good practice to do code reviews. They should be done by you and the other core developer whenever something is about to change in your common library code.

Before any changes are to be included either you or the other core developer must sign off the code. Then and only then should the change be merged into the trunk.

Be careful of changes that break unit tests on the public side of the api, in that case you should change the api's version. A good idea is to follow semantic versioning like it is suggested in the comments.

Be strict about this.


答:
Actually, as mentioned, what if it's position changes?  What you could/should do is use a code, rather than rely on index.

So, when you create your select list it ends up with html like

```<code><select>
    <option value='CREATE'>Create New Vendor...</option>
    <option value='1'>Existing Vendor</option>
    <option value='2'>Existing Vendor 2</option>
    <option value='3'>Existing Vendor 3</option>
</select>
</code>```

Then instead of checking for selectedIndex === 0, check that the the value is CREATECODE which would be in a constant and would have been used for both this test, and when creating the select list.

Body:
Actually, as mentioned, what if it's position changes?  What you could/should do is use a code, rather than rely on index.

So, when you create your select list it ends up with html like

<select>
    <option value='CREATE'>Create New Vendor...</option>
    <option value='1'>Existing Vendor</option>
    <option value='2'>Existing Vendor 2</option>
    <option value='3'>Existing Vendor 3</option>
</select>

Then instead of checking for selectedIndex === 0, check that the the value is CREATECODE which would be in a constant and would have been used for both this test, and when creating the select list.


答:
I would get rid of it altogether.  Just put a create new button next to the combo box list.  Double click an item in the list to edit, or click the button.  Don't have the new functionality buried in the combobox.  Then the magic number is removed altogether.

In general any literal number in code should be defined as a constant so as to put context around the number.  What's zero mean?  In this case 0 = NEW_VENDOR.  In other cases, it might mean something different, so it is always a good idea for readability and maintainability to put some context around it.


问:
How to update display during large processing job
I have an ASP.NET C# application that needs to go off and iterate through a directory of .xml files and do some processing on the data inside them. This is easy enough, but i need to display the result after each .xml is processed, how can this be done?

What im really asking here is how do you process a lot of data in a loop that needs to be displayed back to the client even though the server processing has not fully completed. Is this even possible?

I could start the big process in a seperate thread and start a js timeout to postback and essentially poll the process but this doesn't sound great and would probably require using static variables to maintain state.

Would it be correct to use SessionState / ViewState / QueryString to persist the status of which file ive processed and do away with the loop altogether? Therefore seperate the large job into seperate requests?

答:
The bottom line here is that if you are a server, you can't maintain a persistent connection with your clients.  This means that your solution has got to be based on some sort of polling.  I would structure it like this:

Client clicks on "Start Processing" or similar.

As a result, there is a Javascript AJAX call to a WebMethod on the server.

WebMethod begins the processing, and thenreturns the result of processing the first file when ready.

Client receives the response to the service call containing the result of processing the first file, displays this response, and then requests the next result.

Server returns the next result of the processing, and the loop continues.

The caveat to this, naturally, is dependent on how the latency of your client/server connection compares to the average time taken to process each file.  Also, do you have to show the user the result of each processing, or is it OK if one is skipped because the processing loop is iterating faster than the display update loop.  You could always tie them together, so that the server does not process the next file until it receives a request to do so from the client.