答:
Any formal review should be undertaken on source files that are under configuration control, and the review records clearly stating the revision of the file.

This avoids any "you haven't got the latest file" type arguments, and ensures everyone is reviewing the same copy of the source-code.

It also means that, should any post-review corrections be required, the history can be annotated with that fact.

Title: Review before or after code commit, which is better?

Body:
Traditionally we performed code review before commit, I had an argument with my colleague today, who preferred code review after commit.

First, here's some background,

We have some experienced developers and we also have new hires with almost zero programming experience.

We'd like to perform fast and short iterations to release our product.

All team members are located at the same site.

The advantages of code review before commit I've learned:

Mentor new hires

Try to prevent errors, failures, bad designs early in the development cycle

Learn from others

Knowledge backup if someone quits

But I've also had some bad experiences:

Low efficiency, some changes may be reviewed over days

Hard to balance speed and quality, especially for newbies

One team member felt distrust

As to post-commit review, I know little about this, but the thing I'm most worried about is the risk of losing control due to lack of review.
Any opinions?

UPDATE:

We're using Perforce for VCS

We code and commit in the same branches (trunk or bug fixing branches)

To improve efficiency, we've tried to split code into small changes. We've also tried some live dialog review, but not everyone followed the rule. This is another problem though.


问:
Depending on fixed version of a library and ignore its updates
I was talking to a technical boss yesterday. Its about a project in C++ that depends on opencv and he wanted to include a specific opencv version into the svn and keep using this version ignoring any updates which I disagreed with.We had a heated discussion about that.

His arguments:

Everything has to be delivered into one package and we can't ask the client to install external libraries.

We depend on a fixed version so that new updates of opencv won't screw our code.

We can't guarantee that within a version update, ex from 3.2.buildx to 3.2.buildy.

Buildy the function signatures won't change.

My arguments:

True everything has to be delivered to the client as one package,but that's what build scripts are for. They download the external libraries and create a bundle.

Within updates of the same version 3.2.buildx to 3.2.buildy its impossible that a signature change, unless it is a really crappy framework, which isn't the case with opencv.

We deprive ourselves from new updates and features of that library.

If there's a bug in the version we took, and even if there's a bug fix later, we won't be able to get that fix.

Its simply ineffiecient and anti design to depend on a certain version/build of an external library as it makes our project difficult in the future to adopt to new changes.

So I'd like to know what you guys think. Does it really make sense to include a specific version of external library in our svn and keep using it ignoring all updates?

答: The buzz words defining your argument are "continuous integration."  It is more pain in the short term, but the reason you do it is to save even more pain in the long term.  Even though there may be nothing new you want from the package right now, the longer into the future you go, the more likely there will be a feature or bug fix you do want.  What happens when people privately fork a project is that now to get that feature you're pulling in years of changes all at once, and you may have no idea what some of them are.  A small list of changes every week is much easier to deal with.  When people talk about problems with upgrades of third party libraries, they're talking about the huge upgrades, not from yesterday's daily build to today's.</p>

ContentLicense: CC BY-SA 3.0


问:
What can I do to make sure my code gets maintained in a developer light environment?
I am a contract data analyst, so I bounce between jobs every 3-6 months, which I find to be a good fit for me, but it leads to some problems when it comes to coding. I mostly do statistics (I've asked a similar question on cross validated, but the answers there are not relevant here), but I have also found out that the business world loves excel and loves copying and pasting the same thing over and over again even more. This led me to learn how to write VBA scripts and then VB.NET programs to automate as many of these reports as I can.

I am certain my programs are not the most elegant, but I put a good bit of effort into making sure they work under as many cases as I can test, I add in exceptions and try to code so the program can handle changes in the files that it processes, but there is a limit, if you remove a huge portion of the data, there is a good chance my program is going to trip up, which I accept will inevitably happen. Usually a pretty minor change in the code fixes the problem and I do try and comment my code and make it readable under the assumption that some other person will have to read it some day.

My problem is that I generally get put on teams of folks with essentially no experience with programming (like VBA would be a huge stretch for anyone I work directly with). I am wondering what I should be doing as the person that wrote the code to do my best to keep it maintained. I have two approaches in mind (outlined next), but would be very happy to get any advice.

Solution 1: Find the more tech savvy coworkers and run them through the programs and what basic changes can be made. Honestly automating excel is about as easy as it can get when it comes to programming, so I feel like I could teach someone the basics of maintaining it pretty quick.

Solution 2: Get in touch with the IT department and show them what is going on and maybe they will be able to help. The problem here is that the IT department is constantly swamped (as I'm sure many of you know) and I feel like kind of a jerk for dumping more things on them.

I do leave my personal email address with places and am willing to answer quick questions via email, but I view the need for more exhaustive maintenance as something of an inevitability and would like to make sure I do my due diligence to make sure it gets done. I imagine some combination of the two approaches outlined there, but is there any kind of heads up I should give IT? I feel like I would be annoyed if I started getting requests to fix a program that I had never seen from some random guy that is no longer there.

答:
Isn't this up to the customer? They hired you for a reason: either they don't have your expertise or they don't have the time.

As long as you make them aware of the situation, it's up to them. They may prefer to just hire you back. Of course they'll try and get some free advice. You don't seem to mind the minor questions, so it's not like you're always gouging them for billable hours.

If a company wants to continue to add features and functionality, they'll eventually need a programmer. Most people could learn how to change a car's oil and save money, but they just don't want to crawl under the car.


问:
What are some general guidelines for setting up an iOS project I will want to personally publish but sell in the future?
I have an idea for a personal iOS project that I would like to write and release to the iOS store.  I'm the type of developer who enjoys developing and publishing.  I want to write quality software and take care of my customers.  Assuming that I wrote an application that had reasonable success, there is a fair chance that I would want to sell the ownership rights of the app to another party and I'd use the proceeds to develop my next personal project which, in turn, I'd probably want to sell in the future.

With that said, what are some general guidelines for creating, making and publishing an iOS project that I will eventually want to transfer to another company/developer?

I know this is a bit of a broad question, but I request that the given advice be a general list of tips, suggestions and pitfalls to avoid.  If any particular bullet point on your list needs more explanation, I'll either search for the answer or post a new question specific to that requirement.

Thank you!

Note Regarding this Question

I am posting this question on Programmers.SO because I think that this is an issue of software architecting, seeking advice for setting a new application project and publishing a project to the Apple iOS store-- all within the requirements for questions on this site.

UPDATE - 2012-09-14

I would further like to request that if anyone is aware of a good article on a case study of such a transition, I would consider that a good answer as well.  Such an article may not have all the answers, but it could outline quite a few of the pitfalls which should be avoided.

Apps are sold to other holding companies on a semi-frequent basis.  Often, it happens when a small app becomes a runaway success and a bigger company wants to purchase the ownership and rights.

I've had difficulty finding any information on this topic (probably my poor googling skills.) Most keywords that I tend to search also relate to promoting an app so that people will download it.  Thanks for your insight.

答:
The easiest thing from the app store perspective is to set up a holding company that owns the rights to the app (the brand, source code and any other materials) and which has its own iTunes Connect account. When it comes time to sell the app you sell that company and transfer ownership of the account to the new owner.

This was covered recently by Marco Arment on Build and Analyze. I think it was number 93 but I could be wrong.


问:
Are costs part of the requirements?
I am new to requirements analysis and have a simple questions: Would you include the budget in the requirements, if e. g. the departments budget for running costs is 10k a year. </p>

答:
No.

A functional requirement is one that the product must have to provide the capability needed by the ultimate user.¹

A nonfunctional requirement is a quality or property that the product must have.¹

Both are about the software itself, and not the management. Cost of producing the software has nothing to do in the requirements, since it doesn't describe the software itself and is not inherent to the software product, but to people.

Requirements should also be testable, which makes it impossible to include even maintenance costs. For example, how you would be able to verify, objectively, that the following requirement passes for a current version of software product?

The maintenance cost is inferior to $5 000 per year for the next ten years, the maintenance task being limited to the migration of the product to new hardware, performance monitoring, clearing of old logs and audit records, clearing of personal information about unregistered users and processing of legal requests related to the personal data collected by the product.

¹ Definitions taken from Managing Information Technology Projects: Applying Project Management Strategies to Software, Hardware, and Integration Initiatives by James Taylor, ISBN: 0814408117.

Title: Are costs part of the requirements?


问:
Simple vs Complex (but performance efficient) solution - which one to choose and when?
I have been programming for a couple of years and have often found myself at a dilemma.

There are two solutions -

one is simple one i.e. simple approach, easier to understand and maintain. It involves some redundancy, some extra work (extra IO, extra processing)   and therefore is not the most optimal solution.

but other uses a complex approach,difficult to implement, often involving interaction between lot of modules and is a performance efficient solution.

Which solution should I strive for when I do not have hard performance SLA to meet and even the simple solution can meet the performance SLA? I have felt  disdain among my fellow developers for simple solution.

Is it good practice to come up with most optimal complex solution if your performance SLA can be met by a simple solution?

答:
Is it good practice to come up with most optimal complex solution if
  your performance SLA can be met by a simple solution?

Optimal is an ambiguous word!

Ultimately, if there is much risk in having to maintain the complex one, and if the simple one is "good enough" I'd always err on the side of the simple one.

Add in any risk of the complex one not being good enough, then KISS is probably the right answer.


答:
In general, software project requirements do not include pricing.

Pricing is generally included in project bidding document for the project. Other than that, all the requirements are written to specify what is expected to be done.

Title: Are costs part of the requirements?

Body: I am new to requirements analysis and have a simple questions: Would you include the budget in the requirements, if e. g. the departments budget for running costs is 10k a year. </p>


问:
Best practice for packing Java enums?
What is the best practice for packaging Java enums?

is it separate file for each enum?

 or

having same file for all the enums?

What are the pros and cons ?

答:
First, an overriding rule is that if an enum is public, it must be declared in a file of its own. This is a Java rule that applies to all classes, interfaces, and enums, which cannot be broken.

For non-public enums, you should follow the same rule, except when multiple enums are closely connected.

For example, if you are building an expression processor and declaring an enumeration for an expression sub-type, a binary expression sub-type, and a unary expression sub-type, you may want to group the three enumerations together in a single file.

Title: Best practice for packing Java enums?


答:
Simplicity is prerequisite of reliability. If you have a simple solution that works, by all means go for it! It is much easier to optimize a working program than to make an optimized program work. Also do not forget about Moore's law: if your simple solution meet the performance goals today, it will probably crush them1 in a year or two.

1 There's no guarantee there, because as Jimmy Hoffa noted in his comment below, Moore's law has its limits.

Title: Simple vs Complex (but performance efficient) solution - which one to choose and when?

Body:
I have been programming for a couple of years and have often found myself at a dilemma.

There are two solutions -

one is simple one i.e. simple approach, easier to understand and maintain. It involves some redundancy, some extra work (extra IO, extra processing)   and therefore is not the most optimal solution.

but other uses a complex approach,difficult to implement, often involving interaction between lot of modules and is a performance efficient solution.

Which solution should I strive for when I do not have hard performance SLA to meet and even the simple solution can meet the performance SLA? I have felt  disdain among my fellow developers for simple solution.

Is it good practice to come up with most optimal complex solution if your performance SLA can be met by a simple solution?


答:
Which solution should I strive for when I do not have hard performance SLA to meet and even the simple solution can meet the performance SLA?

The simple one. It meets spec, it's easier to understand, it's easier to maintain, and it's probably a whole lot less buggy.

What you are doing in advocating the performance efficient solution is introducing speculative generality and premature optimization into your code. Don't do it! Performance goes against the grain of just about every other software engineering 'ility' there is (reliability, maintainability, readability, testability, understandability, ...). Chase performance when testing indicates that there truly is a need to chase after performance.

Do not chase performance when performance doesn't matter. Even if it does matter, you should only chase performance in those areas where the testing indicates that a performance bottleneck exists. Do not let performance problems be an excuse to replace simple_but_slow_method_to_do_X() with a faster version if that simple version doesn't show up as a bottleneck.

Enhanced performance is almost inevitably encumbered with a host of code smell problems. You've mentioned several in the question: A complex approach, difficult to implement, higher coupling. Are those really worth dragging in?


答:
When evaluating two approaches, one being simpler but less efficient while other being more complex and more efficient, one has to consider the problem and the project domain.

Consider a multi-billion software project for healthcare industry which has planned lifetime for over 15 years of maintenance and +20 years of use. In such a project performance is definitely not going to be a concern, but project complexity and structure can cause major problems for the maintenance of the project, which lasts for that 15 years at minimum. Maintainability and simplicity come before anything.

Then, consider another example. A console game engine which is supposed to power the upcoming games of the company for the next 5+ years. Because games are extremely resource-constrained programs, efficiency goes before maintainability in many cases. Writing your very own, very specific data-structures and algorithms for some task can be very important even if it goes against any kind of "best practices" of software development. A good example of this could be Data Oriented Design in which you store your data in similar data arrays, rather than in actual objects. This is to increase reference of locality and as such increase CPU cache efficiency. Not practical, but very crucial in the given domain.


答:
Take a lesson from Knuth here: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil".

Think about your solutions in this order: First, always, correctness. Second, improve clarity and simplicity. Third, and only when you can demonstrate the need, efficiency.

Adding efficiency will almost always cost you something important, and so should only be pursued when you know you need to.


答:
This is always a hard question and I see answers swinging one way, so I'll play the game for the other side, though I don't claim either answer is correct, it's a very soft and case-by-case topic.

One thing about a complex but high performance solution is you can always just document the ever living heck out of it. I'm generally a fan of self-documenting code, but I'm also a fan of software that responds in an amount of time that makes me feel like it's not slowing me down. If you do go with the complex but high performance solution, consider what you can do to make it not so bad:

Wrap it in an interface, put it in an assembly on it's own, possibly even a process all it's own. Make it as loosely coupled as possible with as thick an abstraction wall around it as possible to avoid leaks. Write lots of unit tests for it to save regressions in the future.

Document it in the code, even consider writing some real documentation. Think about complex data structures and how they're documented, imagine trying to understand the implementation of one of them from code without a data structures book/wikipedia article to explain it. And yet we all accept that these complex data structures are in fact good things and it's beneficial that someone did implement them in our languages.

Remember that we're all sending messages on a TCP/IP stack that is likely as harry as code can get if any of us were to look at it, expressly so it performs the way we all require it too. Perhaps your problem doesn't require this level of optimization, perhaps it does, but beware when tackling this question as we all have to from time to time: There be dragons there.


问:
WINAPI beginner guidance question
I'm learning to develop windows applications using WINAPI and plain C.

Now I got a bit confused with all those handles and would like to ask if you guys could teach me some good practices to structure and handle controls and windows.

Here's where I get confused:

Using the IDs declared in the resources for each object, we can get their handles using GetDlgItem(). Now what if we don't know their parent, which is needed by this function.

One example: We have the main window created at launch. Then we register two new window classes and create a window for each new class and we create a message function for each too.
Now if inside one of the children windows I create a button and inside the other child window I create a text label. Now when we click the button inside of child window A the label in child window B shall be modified to whatever.

The WM_COMMAND for the button is interpreted inside the message loop for child window A. Now what would be the best and more elegant way to access the text label inside the child window B?

I am in the process of learning the WINAPI and just want to learn it right from the start instead of producing Hacked code that someday becomes unreadable and to later have to adapt to a new way of programing.

Is there really no one able to give me some advice?

答:
About a year ago I stumbled on a book at work that was about to be thrown away.  It was called
Windows Wisdom: For C and C++ Programmers
ISBN: 0471940046

The book presents a problem, and then provides a number of different approaches and solutions to the problem.  If it were published today it would most likely be called "WINAPI Recipes" or "WINAPI Cookbook".  Its that type of book.

The book is out of print but you should be able to find a used copy for cheap.

Instead of regurgitating the contents of the book, I wanted to point you at the source.  I believe it may provide the general guidance that you are looking for.

Title: WINAPI beginner guidance question


答:
I'd prefer the simple one. In my opinion the premature optimizations cause as much problems as they solve. In many cases good design allows you to change given implementations in the future, if they become bottlenecks.

So at the bottom line - I'll design it as flexible as possible, but won't sacrifice simplicity for flexibility too much.


答:
Short Answer: Prefer the simple solutions over complex, and remember KISS and YAGNI principles

Because initial project requirements and software is never perfect, it requires changes as application is developed/used. Iterative approach in development phases is a very good match to start things simple and extend it as needed. The simplest solutions have room for flexibility and more easy to maintain.

In addition, trying to be smart and placing some add-hoc optimization while still building your application is not a good practice and may over-complicate your solution. As it is known, "premature optimization is the root of all evil" - from Knuth's book


答:
Which one costs less?

Most of the time, a simple solution that's slightly slower will be perfectly acceptable in terms of performance, and simplicity makes it cheaper to develop, maintain, and eventually replace.

On the other hand, sometimes speed is really important, and the financial gain that comes from even small speed improvements can be far greater than the increased cost of a more complicated solution. For example, shaving 0.01s off the time to complete a transaction can make a securities trading system much more profitable. A 10% improvement in efficiency of a system that supports several million users could mean a significant reduction in server costs.

So, the question you have to ask yourself is: Does using the complex solution have enough of an impact on the bottom line to pay for its additional cost? Actually, you should probably ask your client to decide since they're paying the bills and reaping the potential benefits. One good option is to go with the simple solution first, and offer the more complex solution as a possible improvement. That lets you get your system up and running and gives your client something to start testing, and that experience may inform the decision to implement (or not implement) the more complicated solution.


答:
Enums are classes so you should pack them as ordinary classes.
If the enum is used in many places inside the package then put it in a single file. If the enum is strongly linked with a class, then put it as a public (or protected) static inner class.

I do not see reasons for placing all the enums in a single file unless they are related.

Title: Best practice for packing Java enums?

Body:
What is the best practice for packaging Java enums?

is it separate file for each enum?

 or

having same file for all the enums?

What are the pros and cons ?


答:
In my experience, the "right" way is somewhere in the middle. I've had the pleasure to work on both radical ends of the spectrum, and none of them were any good.

On one project we had an inexperienced lead who wanted to keep things updated for the same reason you state -- to not fall behind in the long term. Aside from the problem that we had to check our own code (though with decent code coverage, it's not that big a deal), the biggest problem is that the library is not community-tested when it's released. The project lead got burned when clients found a bug in the framework we were using, and short of submitting patches to the framework, there was nothing we could do.

Another project I've had to work on is something that I remember as probably the worst nightmare of my programming career. The guys before me had decided that "updating will only introduce bugs". So when I came along ~ mid 2010, it had Hibernate v2.1.0 and Maven v1.0.1, for both of which it was even a pain to get documentation. It was at that point that we started needing native SQL queries (it's near impossible to do analytic functions through Hibernate without that) and native SQL was almost impossible for that version.

Now imagine upgrading a core part of a decent size enterprise project with close to no test coverage from a 2004 version of a framework to a recent one.

Title: Depending on fixed version of a library and ignore its updates

Body:
I was talking to a technical boss yesterday. Its about a project in C++ that depends on opencv and he wanted to include a specific opencv version into the svn and keep using this version ignoring any updates which I disagreed with.We had a heated discussion about that.

His arguments:

Everything has to be delivered into one package and we can't ask the client to install external libraries.

We depend on a fixed version so that new updates of opencv won't screw our code.

We can't guarantee that within a version update, ex from 3.2.buildx to 3.2.buildy.

Buildy the function signatures won't change.

My arguments:

True everything has to be delivered to the client as one package,but that's what build scripts are for. They download the external libraries and create a bundle.

Within updates of the same version 3.2.buildx to 3.2.buildy its impossible that a signature change, unless it is a really crappy framework, which isn't the case with opencv.

We deprive ourselves from new updates and features of that library.

If there's a bug in the version we took, and even if there's a bug fix later, we won't be able to get that fix.

Its simply ineffiecient and anti design to depend on a certain version/build of an external library as it makes our project difficult in the future to adopt to new changes.

So I'd like to know what you guys think. Does it really make sense to include a specific version of external library in our svn and keep using it ignoring all updates?


答: Cost typically isn't listed among the functional requirements for software. That's at least partly because either only one copy of the product is needed, or because the marginal cost -- the cost of creating additional copies -- is close to $0 for software. However, per-unit cost can certainly be a requirement for other types of products. If you're designing the software for, say, a remote control, you only need to know what hardware you have to work with. If you're designing the entire device, on the other hand, you need to know how much the client is willing to pay to produce each additional device so that you can choose components that let you meet the functional requirements without losing money.</p>

Title: Are costs part of the requirements?


问:
How best to store images on a file system
Developing an application in which users have to upload images. I have not really got much experience with file uploads in an application so I am wondering what the best way is for storing images which are uploaded by users to the file system. </p>

答:
Images are just files, so you could store them as-is, as you would store any other file.

However, you may want to transform them a little.  For example, most digital cameras these days produce absurdly high resolution files, e.g. 2000 pixels across.  Most users don't know how to shrink them to something more manageable, and even if they did, they don't have the time (or can't be bothered.)  So you may want to allow people to upload large images, then shrink them.

Also, what will you do with the images?  Display them on a web page?  There are only certain formats that work on a web page, e.g. if someone uploaded a TIFF image, you might want to convert it to JPEG or PNG.

Finally, you might want to increase compression.  If someone sends you an image that's a reasonable resolution, but they're turned all the "quality" options up to 11, it will still be a big file.  You might want to compress it more to make it a smaller file.

A final consideration: if you're going to do any image manipulation, you might want to put all images into the same format, e.g. JPEG at a certain resolution and compression level, so your image manipulation only has 1 format to deal with.


答:
The storage strategy should, in most cases, follow from the conceptual design of the site that requires image storage, and the expected number of users. We'll need more information, I think; are you creating a site like Photobucket or Flickr, designed primarily to be an image-hosting site? Or are the images a secondary concern, such as being attachments to messages? How many images do you foresee having to store? How many users will this system have?

Two popular strategies I know of and have used involve a SQL database, to provide better concurrency than a flat file system. You have a table, representing the images in the DB. That table then either has a "BLOB" (binary large object) column that stores the actual byte data of the image, or a string that holds the path to the image in a flat file system elsewhere. Either way, scanning for data about images is highly parallelizable. Storing images on disk is more straightforward, and reduces the size of the DB, but lowers performance in high user-count situations. Storing images as DB data is the opposite.

Title: How best to store images on a file system

Body: Developing an application in which users have to upload images. I have not really got much experience with file uploads in an application so I am wondering what the best way is for storing images which are uploaded by users to the file system. </p>


问:
When creating a library for a simple program, what must I do to protect others from its lack of thread safety?
When creating a library for a simple program, is it more cost effective to make it thread safe or is there a way to detect the program's use in a multithreaded program and ASSERT() or otherwise determine (preferably at compile or link time) that it may create problems.

Related help for this question would be automated tool support for finding potential problems with thread safety, programming language features that enforce it,

答:
Something like this (C#) MIGHT do the trick...

```<code>public class MyNonThreadSafeClass()
{
   public MyNonThreadSafeClass()
   {
       currentThreadId = Thread.CurrentThread.ManagedThreadId;
   }

   private readonly int currentThreadId;

   public void SomeNonThreadSafeMethod()
   {
      AssertSameThread();

      //do your thing
   }

   private void AssertSameThread()
   {
      if(currentThreadId != Thread.CurrentThread.ManagedThreadId)
         throw new InvalidOperationException("Method must be called on the same thread that created the containing object");
   }
}
</code>```

This would ensure that only the thread that created the object instance could work with it. Variations of this could ensure that no one method is called concurrently by different threads at the same time (but allow one thread to create the instance and then give it to another thread to work with), or that the creating thread must have a message pump (and is thus a UI thread and so very likely to be the app's "main" thread).

However, overall, if you expect your library to be used by parallel threads of a process, and want to support that, I would make it thread-safe. It's not really that hard; use monitors, mutexes or other locks to protect shared state, and favor "pure functions" that don't rely on instance-scoped state.

Body:
Something like this (C#) MIGHT do the trick...

public class MyNonThreadSafeClass()
{
   public MyNonThreadSafeClass()
   {
       currentThreadId = Thread.CurrentThread.ManagedThreadId;
   }

   private readonly int currentThreadId;

   public void SomeNonThreadSafeMethod()
   {
      AssertSameThread();

      //do your thing
   }

   private void AssertSameThread()
   {
      if(currentThreadId != Thread.CurrentThread.ManagedThreadId)
         throw new InvalidOperationException("Method must be called on the same thread that created the containing object");
   }
}

This would ensure that only the thread that created the object instance could work with it. Variations of this could ensure that no one method is called concurrently by different threads at the same time (but allow one thread to create the instance and then give it to another thread to work with), or that the creating thread must have a message pump (and is thus a UI thread and so very likely to be the app's "main" thread).

However, overall, if you expect your library to be used by parallel threads of a process, and want to support that, I would make it thread-safe. It's not really that hard; use monitors, mutexes or other locks to protect shared state, and favor "pure functions" that don't rely on instance-scoped state.


问:
Development-led security vs administration-led security in a software product?
There are cases where you have the opportunity, as a developer, to enforce stricter security features and protections on a software, though they could very well be managed at an environmental level (ie, the operating system would take care of it).

Where would you say you draw the line, and what elements do you factor in your decision?

Concrete Examples

User Management is the OS's responsibility

Not exactly meant as a security feature, but in a similar case Google Chrome used to not allow separate profiles. The invoked reason (though it now supports multiple profiles for a same OS user) used to be that user management was the operating system's responsibility.

Disabling Web-Form Fields

A recurrent request I see addressed online is to have auto-completion be disabled on form fields. Auto-completion didn't exist in old browsers, and was a welcome feature at the time it was introduced for people who needed to fill in forms often. But it also brought in some security concerns, and so some browsers started to implement, on top of the (obviously needed) setting in their own preference/customization panel, an autocomplete attribute for form or input fields. And this has now been introduced into the upcoming HTML5 standard. For browsers that do not listen to this attribute, strange hacks* are offered, like generating unique IDs and names for fields to avoid them from being suggested in future forms (which comes with another herd of issues, like polluting your local auto-fill cache and not preventing a password from being stored in it, but instead probably duplicating its occurences).

In this particular case, and others, I'd argue that this is a user setting and that it's the user's desire and the user's responsibility to enable or disable auto-fill (by disabling the feature altogether). And if it is based on an internal policy and security requirement in a corporate environment, then substitute the user for the administrator in the above.

I assume it could be counter-argued that the user may want to access non-critical applications (or sites) with this handy feature enabled, and critical applications with this feature disabled. But then I'd think that's what security zones are for (in some browsers), or the sign that you need a more secure (and dedicated) environment / account to use these applications.

* I obviously don't deny the ingeniosity of the people who were forced to find workarounds, just the necessity of said workarounds.

Questions

That was a tad long-winded, so I guess my questions are:

Would you in general consider it to be the application's (hence, the developer's) responsiblity?

Where do you draw the line, if not in the "general" case?

答:
Interesting question.

As a developer it's natural to want to draw the lines of responsibility in a logical and efficient way based on who implemented the functionality.  Sadly, users care very little who is responsible for a program not working the way the they want it to.  And the users are the source of your compensation, so as a practical matter if they don't want to take care of the issue via administration, it's the developer's problem.

Where you draw the line is where your customer draws the line.  If they feel the existence of an administrative solution makes paying for development not worthwhile, then you go with the administrative solution.


问:
Should concrete classes avoid calling other concrete classes, except for data objects?
In Appendix A to The Art of Unit Testing, Roy Osherove, speaking about ways to write testable code from the start, says,

An abstract class shouldn't call concrete classes, and concerete classes shouldn't call concrete classes either, unless they're data objects (objects holding data, with no behavior). (259)

The first half of the sentence is simply Dependency Inversion from SOLID. The second half seems rather extreme to me. That means that every time I'm going to write a class that isn't a simple data structure, which is most classes, I should write an interface or abstract class first, right? Is it really worthwhile to go that far in defining abstract classes an interfaces? Can anyone explain why in more detail, or refute it in spite of its benefit for testability?

答:
That means that every time I'm going to write a class that isn't a simple data structure, which is most classes, I should write an interface or abstract class first, right?

Yup.

Is it really worthwhile to go that far in defining abstract classes an interfaces?

No, but you should err toward more interfaces than less.

Can anyone explain why in more detail, or refute it in spite of its benefit for testability?

I would argue that it is fine to use concrete classes directly as long as those concrete classes are not part of the interface that the consumer is implementing/providing. As soon as they're part of the public interface rather than the implementation of a module, they either need to be abstracted or they need to be stable enough that you're sure that code isn't going to need to change or be polymorphic.


答:
I don't think he means you should write an abstract class for each class, necessarily.  I think he means there should be a way to substitute a test class for the concrete class.  This might be done via a DI container, for example.

It's usually worthwhile to go that far because you are usually going to actually write a test that substitutes a test class for the concrete class, but if you don't need the test then you don't need to bother.

Title: Should concrete classes avoid calling other concrete classes, except for data objects?

Body:
In Appendix A to The Art of Unit Testing, Roy Osherove, speaking about ways to write testable code from the start, says,

An abstract class shouldn't call concrete classes, and concerete classes shouldn't call concrete classes either, unless they're data objects (objects holding data, with no behavior). (259)

The first half of the sentence is simply Dependency Inversion from SOLID. The second half seems rather extreme to me. That means that every time I'm going to write a class that isn't a simple data structure, which is most classes, I should write an interface or abstract class first, right? Is it really worthwhile to go that far in defining abstract classes an interfaces? Can anyone explain why in more detail, or refute it in spite of its benefit for testability?


答: Its only worth going to those extremes if you drink the unit testing/TDD Kool-Aid.  To make unit testing easier to accomplish certain designs have to be followed. Some of these designs go against traditional OO design concepts. It is up to you to decide whether the potential gains from unit tests out weigh the cost of having to make some poor design considerations. Unit tests are far from the silver bullet many try to make them out to be, but it is the current design fad.</p>


问:
Advantages of paid Java Application Servers?
What are the advantages of Weblogic or Websphere over Glassfish or JBoss, since they may reach costs of millions of dollars?

Edit: Is there additional functionality? The all are Java EE Full Certified.

The question is about technology, not business or marketing. From the technological POV how are the servers different?

答: There is certainly no technical benefit at all to Websphere or Weblogic. It's the perception that going with IBM or Oracle as your vendor is the safe choice.</p>


问:
Web Frameworks caring about persistence?
I have noticed that Play! Framework encompasses persistence strategy (like JPA etc...)

Why would a web framework care about persistence ?!

Indeed, this would be the job of the server-sides components (like EJB etc...), wouldn't this?

Otherwise, client would be too coupled with server's business logic.

UPDATE: One answer would be : it's more likely used for simple application including itself the whole business logics. However, for large applications with well-designed layers(services, domain, DAO's etc..), persistence is not recommended within web client layer since there would be several different web(or not) clients.

答:
If the framework is used as part of an application that involves a database back-end, then it may be useful to have persistence of the data in a form that doesn't require the physical database.

For example, I can remember a previous workplace that used Fluent nHibernate as the ORM tool that would be used translate database tables to objects.  This would be one example.

Given that Play! is built in Java, it would appear to be a server-side component thus making that 3rd line add little value to the question, IMO.

To elaborate a bit more, I see a few pieces together and this is where persistence plays a role:

The system has a Web UI component that makes web pages for the user.

The system has a database component where stuff is stored where various CRUD operations are performed.

There is the desire to test components independently of each other.

Thus, to test the Web UI component without having the database requires one to construct something to mimic being the database which is what the persistence piece usually is.


问:
Is the singleton pattern prone to thread safety problems?
Is the singleton pattern prone to thread safety problems?  If so, what are the best methods to work around them?</p>

答:
It is heavily depend on the programming language specification & how thread safety is you implemented.

For example: code provided below uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs.

```<code>public class Singleton {
        private static volatile Singleton instance = null;

        private Singleton() {   }

        public static Singleton getInstance() {
                if (instance == null) {
                        synchronized (Singleton.class){
                                if (instance == null) {
                                        instance = new Singleton();
                                }
                      }
                }
                return instance;
        }
}
</code>```

Here is a referencing article on how to correctly implement thread safe Singleton Pattern in C#.

Body:
It is heavily depend on the programming language specification & how thread safety is you implemented.

For example: code provided below uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs.

public class Singleton {
        private static volatile Singleton instance = null;

        private Singleton() {   }

        public static Singleton getInstance() {
                if (instance == null) {
                        synchronized (Singleton.class){
                                if (instance == null) {
                                        instance = new Singleton();
                                }
                      }
                }
                return instance;
        }
}

Here is a referencing article on how to correctly implement thread safe Singleton Pattern in C#.


答:
If well implemented, with threading in mind, a singleton will be thread safe.

There are many implementations in many languages that are not thread safe - see this article by Jon Skeet regarding Singleton in C#. Most of the implementations suffer.

The best ways to "work around them" is to know your language, how it works with threads and ensure the code is thread safe.

Just to note - even if singletons were somehow thread safe by nature, you should not use them for this reason. They tend to be overused and make for un-testable code as a source of global state.

Body: Is the singleton pattern prone to thread safety problems?  If so, what are the best methods to work around them?</p>


答:
Yes, as other answers have noted, it can be implemented in a thread safe manner. That said, it tends to be prone to issues since it already requires careful implementation to avoid subtle issues due to initialization order. The possibility of multiple thread access exacerbates these concerns.

And it's still global state. Even if the singleton itself is threadsafe, the reliance on global state tends to add errors to the actual multithreaded code.

Title: Is the singleton pattern prone to thread safety problems?


答:
A good, basic starter strategy is like this:

Make a table called 'images'.  Make sure it has an autoincrementing primary key (we'll call ID).

When a user uploads an image, insert a row into that table, including the original name of the file and the file extension.  You'll probably also track uploading user, date/time, etc.

Get the last insert id from that query.  Save the image to "your-image-path/(ID).(ext)" in the file system.  For ex, "/images/350.png".

(Recommended) You can use the ID as the direct link to the image by making a simple wrapper script that loads the image by ID (thus obscuring the actual file name, or even keeping the images outside of the web directories).  For ex, 'image.php?id=500' or '/image/500'.  In that script, you can use the original file name from the table in the http header so that when they download it gets saved on the client under the original name.

Areas of enhancement:

Thumbnail Support.  On upload, generate a thumbnail, and store it as ".thumbnail.jpg".  Use a wrapper script for thumbnail retreival based on ID.

Hashing directories.  If you expect more than 1000 or so images, you'll want to break them into multiple subdirectories so the file system doesnt get sluggish (the exact point this happens varies by OS and other factors).  So if you have an image ID of 6500, you might store it in "/images/6/6500.png"

Security.  Validate that an uploaded image is an actual image before saving it to disk. This is especially important if you are allowing direct access to the images - you dont want to accept a .php file that can get uploaded and then executed.  Also make sure your web server config is setup to prevent that sort of thing by preventing the execution of scripts from the images directories.


答:
So I guess this is a vote for warning people using the library.

Yes, that is exactly what my snarky comment was. Unless there is a good reason for adding that expense, don't do it. Thread safety is expensive, to the designer, to the developer, to the tester,  and also to the user who doesn't need it. You are guilty of premature optimization unless there is a very good reason to absorb that expense.

Good reason: You are a developer working on a logging library where a single logged item might comprise many lines in the log file, and the logger might be called from multiple threads. The need for thread safety is right there in the requirements, and those requirements make sense.

Bad reason: After doing so well on the logging library, you are made the project lead that amongst other things will develop a random number library. Here the driving requirements are numerical correctness, ease of use, and speed. You, the project lead, decide to add thread safety to the requirements just because ensuring thread safety was so much fun in the logging library project. You've just blown away my need for speed. I might make trillions of calls to the PRNG during an overnight Monte Carlo run. Your library is about as useful to me as is the built-in rand() function.

You build in thread safety because it makes sense and because there is a need for it, and even then you need to be judicious about how you proceed.

Title: When creating a library for a simple program, what must I do to protect others from its lack of thread safety?

Body:
When creating a library for a simple program, is it more cost effective to make it thread safe or is there a way to detect the program's use in a multithreaded program and ASSERT() or otherwise determine (preferably at compile or link time) that it may create problems.

Related help for this question would be automated tool support for finding potential problems with thread safety, programming language features that enforce it,


问:
Why do exclusively outsourcing projects as a company?
A prospective employer told me they took a company level decision to do only outsourcing projects.

I do not understand why they took such a decision and the guy I talked to did not elaborate. He further said only that "their intention is to build software components".

Since they are growing quite fast and reached around 300 employees, shouldn't they be at least open to the possibility of having a project of their own, maybe? All other companies I've had contact with were at least open to have one in the future.

I talked to a few of their employees and some are working in parallel on more than 2 outsourced projects (dividing time something like 4 + 4 hours / day). It seemed like a lot of projects with a period of a few months, maybe half a year come and go.

Why would a company choose to provide only outsourcing services like that? How does it work to keep hundreds of people on outsourced projects with a seemingly high project turnover rate?

答:
A company is providing "services like that" (outsourcing services), because someone else is buying them. It is a completely different discussion if this is proper or not.

What I have seen is that many companies have a person high up in the hierarchy that runs the whole place with "dogmas" or "doctrines". Stuff like "we will only use C#/Java", "only compiled languages" etc. So one possibility is doctrine. The other one is that there is so high market demand that it would make no sense at this point to do otherwise. I would also like to point out a nice opinion on why such stuff happens from Clayton M. Christensen: marginal decision making.

Decision making based on marginal costs, happens when an organisation/person decides based on marginal cost, neglecting what is best for them in the long run (maybe some years from now). For example for the company you mention, doing something "on their own" requires some infrastructure that they simply do not have, so they have two options: either to create/buy it, or to continue what they are doing at the moment. For the next outsourcing project, they might have people waiting (so no extra cost) or can take some people off from something else, or hire a small number, which is not the case of hiring say, a new sales department to sell their new "product".


问:
Resources for popular domain models
I have come across many situations where I had to build a system for a library or a clinic or other popular domains.

The thing is a domain model for a library was probably done 1000 times already with different level of details of course. Here is an example.

Is there a popular website or community where one can find ready made domain models for popular systems?

The whole purpose I'm trying to achieve is to quickly get a grasp of the domain I'm modelling and customise it to my needs. Re-inventing the wheel seems really absurd when the same system might have been modelled properly previously.

Note

I know Google might sound like the perfect source, but it will better if there is a repository out there that people can post there models, so that others can share them.

答:
In my experience, even for a domain type that has been modeled 1000 times before, you cannot rely on a pre-fabricated domain design.

It is certainly true that some domain entities, "Book" or "Fine" in you example, might be common but their roles in the system you are building probably aren't.

Put another way, the requirements gathering for your project is sure to yield different results than the requirements gathering from my project, even in the same domain.

However...

While an exact domain model may not be sharable by every system, a Glossary library might be.

That would be an interesting project too. A community generated and vetted (à la StackExchange) that provided glossaries for entities found in specific domains.

I'd check it out!

My $0.02. Hope it helps.

Title: Resources for popular domain models


问:
Should I store log files in version control
The log files in question are metrics log files.  One of them is a project file produced by SourceMonitor, to which I regularly add checkpoints to chart the progress of projects.</p>

答:
Are they files that change over time?

Is it helpful to be able to retrieve older versions?

Would losing these files be a problem?

If you answered 'yes' to one or more of the above, then sure, go ahead and store them in a version control system. Since you answered 'yes', there's obviously some benefit to be gained by doing so, and little reason not to.

The best argument I can think of against using version control for these files is that log files tend to be linear in nature -- the only way you normally modify them is to append new data to the end of the file. Given that, they have a sort of primitive change tracking mechanism built in, so the added complexity of using version control may not be necessary.


答:
Risk aversion, probably at the very top.

Launching is a risky venture. What if the product fails? Five to ten people years is a million dollars. That's a modest investment. If the product fails, that's a million bucks down the drain. Even if the potential upside is huge, that downside calculation is abhorrent to risk averse people. It's their house, their very very big house, that's on the line.

Compare that to software that some other entity pays the company to develop. Risk of failure is small and manageable. Product failure? That's the problem of the entity that paid for the work. The biggest risk to the company doing the development is whether the cost estimates in the proposal work were correct. With 300 employees, this company most likely has the cost estimation problem pretty well nailed. The potential profits aren't near as great as the profits would be from launching the "next big thing", but 10 percent or so of the net revenues of a 300 employee company is still pretty sweet.

Title: Why do exclusively outsourcing projects as a company?

Body:
A prospective employer told me they took a company level decision to do only outsourcing projects.

I do not understand why they took such a decision and the guy I talked to did not elaborate. He further said only that "their intention is to build software components".

Since they are growing quite fast and reached around 300 employees, shouldn't they be at least open to the possibility of having a project of their own, maybe? All other companies I've had contact with were at least open to have one in the future.

I talked to a few of their employees and some are working in parallel on more than 2 outsourced projects (dividing time something like 4 + 4 hours / day). It seemed like a lot of projects with a period of a few months, maybe half a year come and go.

Why would a company choose to provide only outsourcing services like that? How does it work to keep hundreds of people on outsourced projects with a seemingly high project turnover rate?


答:
There are two approaches that a company that requires some amount of something (accounting, payroll, IT, internal software development) (outside the company's core competency) can take (a former tech company I was employed at laid me off saying "web development is not our core competency").  Either the company will have an internal staff to do the development, or the company will use an outside source for that.

If this something is fairly consistently needed, it tends to make sense to have that be in house.  A large retail company may find that it is more cost effective to hire its own people to do payroll and accounting than it is to outsource those tasks (compare this to a small company with 10 people total on staff where having payroll (done once per month) on staff would be substantial).

On the other hand, if the something is occasionally needed (legal help, IT development) or the staffing levels need to flex from few to lots periodically (tech support with a new release), it may become more cost effective to have that be done outside of the company rather than trying to maintain the staff in house.

Having a person on staff is not cheap.  From things of additional payroll and benefits to less immediately identifiable things of additional facilities (phones, cube floor space).  Additionally, having to staff down with a layoff is not cheap either (severance, California WARN law, paperwork).

When a given task is outsourced, all of those staff is not cheap things get moved to the outsourcing company.  Less floor space is needed in the building, less water is used, etc... and when times get lean it tends to be easy to just say "project is canceled" without having to worry about down staffing at all (or reporting to Wall Street that the company is having a layoff).

In some cases, it may make sense for all of the in house development of internal software to be done externally.  In the development context, there are repercussions to this in terms of quality of the item, ability to support it and turn around time for changes... but in some ways and cases, it may make sense.

So, why would a company be one that only does outsourcing?  Because all of the above companies are hiring them to do it.


问:
By what features and qualities are "free" and "premium"  themes differentiated
I have a lot of time invested in creating Wordpress templates. I want to release combinations of these templates along with different styles and Fancy Front pages as "Premium Wordpress Themes". What I need to know is what does "Premium" mean? What do people expect of a GPL theme vs. a Premium theme? Are there features that are considered required to be premium? Are there features that are in demand but considered "exceptional" i.e. not part of every premium theme? How can I tell the difference?

I have heard tounge-in-cheek answers that say that any theme that makes money is premium, but I mean to ask about what gives an outstanding theme it's quality. Why is it worth more? I am technically able to do many things, but as a lone developer with a family to feed, I can't afford to spend time on features that no one cares about. I have to try to isolate the things that people want. This is serious food and rent to me.

How can I get this kind of info so I can make my project successful?

答:
First, have you tried doing some research?  How many people would know what a GPL theme is?  Do competitors of yours use the term premium in their services?  This is a rather basic point that depending on your target market and location could vary rather dramatically.

Second, what experiments have you tried with labeling different themes into various categories?  Could you take standard themes that have no customizations done and call them something else?

Third, have you considered what kind of return computations and analysis you want to do to determine the proper pricing on this?  For example, how many dollars more over what time period with what changes in support and customizations yield what kind of result?  This is likely a rather hard thing to do and one where you better be prepared to nail down more than a few things here.  For example, if someone wants something special, how do you explain a different pricing for that scenario?  Do you cackle and think, "Ka-ching!" so that the customer wonders what the heck is so funny here?  Do your eyes glaze over like this isn't something important?  Consider the relationship dynamics as part of the equations here.

Those are just some starting questions here that I'd suggest you do some legwork on your own as well as considering what kind of filter do you have for people on-line giving you answers to what is more of a business problem than a technical problem.


答:
Overview

It's a good idea to back up log files, but they do NOT belong in source control!

Good Places For Backups

Burn them encrypted to DVD once a month and pop the DVD in a safe deposit box off-site.

In zip files on a secure drive in a separate secure server room.

Maybe in a secure NoSQL database?

Security

Log files often contain confidential information.  Users can paste their password into the wrong field and have it end up in the logs.  All kinds of information ends up there that's probably covered by Safe Harbor and other international privacy regulations even if it's not otherwise considered private by your customers.  You want to limit the number of people who have access to this stuff and generally all programmers have access to source control.

Size/Speed

Source control is designed for little 100K-5M source files.  Not Gigabytes of logging junk.  Depending on the source control tool you use, you may find yourself waiting for weeks just to get the latest version of your code if you store huge logs in there.

Features

Source control is designed to compare versions.  There is no version comparison like this with log files.  If you need to reference these files quickly and constantly, then log table in a database (either SQL or NoSQL would work) is the way to go.  Version control is just not a good feature-fit for this purpose.

Tools

Gnupg is great for compressing and encrypting huge things.  Use this on the files on the server where the files are generated.  They will transfer faster and be secure when they travel over the wire.

Linux/bash has a logrotate tool, but most logging tools have a logrotate feature that can keep sixty 100Meg files in your log folder just by renaming them .1, .2, .3, etc.  Check how big a file your favorite editor can handle and keep each file a little smaller than that.  Presumably your server drive is backed up and these files with it, but when you upgrade servers (e.g. for an OS upgrade) remember to put a copy of these files somewhere else and restore them to the new server when you are done!

Title: Should I store log files in version control

Body: The log files in question are metrics log files.  One of them is a project file produced by SourceMonitor, to which I regularly add checkpoints to chart the progress of projects.</p>


答:
"Premium" is completely subjective.  There is no industry standard for what it means in a programming or feature context, and in many cases, it is simply used as a buzzword to attract the interest of customers.

What you are looking for is market research, i.e. what do customers want?  It depends largely on your target demographic, and while the results may equate into programmable features to be sold as a "premium" product, the process is not specific to programmers.

From a software engineering perspective, I would recommend surveying your current (or potential) users for information such as the following:

What features of your product(s) do they like

What types of features would they like that you do not currently offer

What features of your product(s) do they wish were different

You could even use something like a Likert scale to help quantify the results, such as:

Rank the following features for attractiveness scale of 1 to 10:

Rank how often you use the following features on a scale from 1 to 10:

Which of the following features (that are not currently offered) would you find most desirable, with 10 being the highest priority:

You could create a great product, but if it does not meet the customers' needs, then it is of little to no value.  Good luck.

Title: By what features and qualities are "free" and "premium"  themes differentiated

Body:
I have a lot of time invested in creating Wordpress templates. I want to release combinations of these templates along with different styles and Fancy Front pages as "Premium Wordpress Themes". What I need to know is what does "Premium" mean? What do people expect of a GPL theme vs. a Premium theme? Are there features that are considered required to be premium? Are there features that are in demand but considered "exceptional" i.e. not part of every premium theme? How can I tell the difference?

I have heard tounge-in-cheek answers that say that any theme that makes money is premium, but I mean to ask about what gives an outstanding theme it's quality. Why is it worth more? I am technically able to do many things, but as a lone developer with a family to feed, I can't afford to spend time on features that no one cares about. I have to try to isolate the things that people want. This is serious food and rent to me.

How can I get this kind of info so I can make my project successful?


答:
Something to consider here is the scale and length of projects the company handles.  If they are generally working for a few years on projects and being able to move from company to company, it could be quite a nice cash cow for them to have an expertise in some other software and not have to work on innovating that software and take advantage of an existing brand.

For example, at a previous workplace, the company bought an off-the-shelf CMS that another company was hired to help with the integration and customization that comes from that system.  We spent a couple of years on that project and so the firm probably made quite a bit of money off of that expertise.  Consider how many software companies customize Oracle, SAP, Microsoft and other enterprise software where they want to get paid for the project and then possibly return years later for a major upgrade that may happen.


问:
Questions about identifying the components in MVC
I'm currently developing an client-server application in node.js, Express, mustache and MySQL. However, I believe this question should be mostly language and framework agnostic.

This is the first time I'm doing a real MVC application and I'm having trouble deciding exactly what means each component.
(I've done web applications that could perhaps be called MVC before, but I wouldn't confidently refer to them as such)

I have a server.js that ties the whole application together. It does initialization of all other components (including the database connection, and what I think are the "models" and the "views"), receiving HTTP requests and deciding which "views" to use.

Does this mean that my server.js file is the controller? Or am I mixing code that doesn't belong there? What components should I break the server.js file into?

Some examples of code that's in the server.js file:

```<code>var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : 'sqlrevenge',
    database : 'blog'
});

//...

app.get("/login", function (req, res) { //Function handles a GET request for login forms
    if (process.env.NODE_ENV == 'DEVELOPMENT') {
        mu.clearCache();
    }

    session.session_from_request(connection, req, function (err, session) {
        if (err) {
            console.log('index.js session error', err);
            session = null;
        }

        login_view.html(res, user_model, post_model, session, mu); //I named my view functions "html" for the case I might want to add other output types (such as a JSON API), or should I opt for completely separate views then?
    });
});
</code>```

I have another file that belongs named session.js. It receives a cookies object, reads the stored data to decide if it's a valid user session or not. It also includes a function named login that does change the value of cookies.

First, I thought it would be part of the controller, since it kind of dealt with user input and supplied data to the models.

Then, I thought that maybe it was a model since it dealt with the application data/database and the data it supplies is used by views.

Now, I'm even wondering if it could be considered a View, since it outputs data (cookies are part of HTTP headers, which are output)

答:
Well, the most certain way to remember the details behind MVC is to learn the MVC song.

http://www.youtube.com/watch?v=YYvOGPMLVDo

Another simple approach is:

If you can see it, it is part of the view.

If it implements business logic, it is the model.

If it converts a gesture or action in the UI to a set operation sent to the model, it is part of the controller.

I also like the description at this page.

http://c2.com/cgi/wiki?ModelViewController


答:
Build a website (if you havent already), put your themes up there and make them available for download. IF you want to give some away, call those "Free", and the ones you want to sell call them Premium, and charge money for them. You will probably also want to offer an Exclusive license which will make that person the owner of that theme, which would mean they pay a lot more, and you remove it from your site.

Premium implies that it is custom, "professional" (in the sense that it stands up to other "commercial" designs), and it's created with the intent that it be great. Sloppy work is generally not accepted as premium work.. although the creator of sloppy work can call it premium. It would just not be as "premium" as other "premium", more refined work.

There are also a lot of sites out there where you can upload your theme to which will pay you when someone pays a fee to downloads them.. In that case you'd be listed in their "premium" section.

I hope you like this premium answer


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

Why implement this in a programming language?

Update:

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

答:
Especially some programmer come from the early days of BASIC, where a variable name can only be 2 characters long.

And so, when it can be any number of characters, they become very happy.  And along with case sensitivity -- because they don't want to also care about SomeName being accidentally equal to SOMENAME and cause a bug due to things like this.

ContentLicense: CC BY-SA 2.5


问:
How should I create a mutable, varied jtree with arbitrary/generic category nodes?
Please note: I don't want coding help here, I'm on Programmers for a reason. I want to improve my program planning/writing skills not (just) my understanding of Java.

I'm trying to figure out how to make a tree which has an arbitrary category system, based on the skills listed for this LARP game here. My previous attempt had a bool for whether a skill was also a category. Trying to code around that was messy. Drawing out my tree I noticed that only my 'leaves' were skills and I'd labeled the others as categories.

What I'm after is a way to make a tree which attempts to separate Model and View, and allow adding an arbitary type of child node (with a separate way of being edited/rendered) to an arbitrary parent.

N.B Everything here is bought as a skill, even where it seems like a property. The End-Users will see this as buying skills (which they do on paper atm) so should be presented as such, all on the same page.

Explanation of tree: The Tree is 'born' with a set of hard coded highest level categories (Weapons, Physical and Mental, Medical and more etc.). From this the user needs to be able to add a skill. Ultimately they want to add the 'One-handed Sword Specialisation' skill (not item) for instance. To do so you'd ideally click 'add' with Weapons selected and then select One-handed from a combobox node that appears on that child, then click add again and enter a name in a text field on that child node that appears. Then click add again to add/specify a 'level' or 'tier' for that leaf; first proficiency, then specialisation (for example).

Of course if you want to buy a different skill it's a completely different route to the leaf. You might not need a combo box at the same level down the tree as you did with the weapon example, and need some other logic behind it too. This is what I'm having trouble getting my head around let alone programming in; how to make a set of classes and not specify what order to attach them together in, but still have them all fit.

What is a good system for describing this sort of tree in code? All the other JTree examples I've seen have some predictable pattern, and mine doesn't. I don't want to have to code this all in 'literals', with long lists of what type (combo-box, text field etc) of children node should be allowed on what parent. Should I be using abstract classes? Interfaces?

How can I make this sort of cluster of objects extensible when I add in other skills not listed above that behave differently?

If there is not a good system to use, is there a good process for working out how to do this sort of thing?

The gears in my head are turning:

I always need to:

Check the parent

Provide options based on the parent

I'm begining to think becasue of this commonality I need some sort of abstract/interface skill class that defines/outlines common methods for skill and category. I can (hopefully) put rules and options in a database and read to-from there. The question is I think now, between an abstract or interface method and how to bes implement that.

答:
I don't think JTree is the right representation for the problem you are trying to solve.  I looked at your web site, and I see lists of stuff.  This is a great start, but I think there is an underlying data design that you may have, but I am not seeing.

Life and Strength look like character attributes to me.  Double, Triple, and Quadruple look like values for the Strength attribute.  Then I see skills divided into Weapon and Medical.  I think of weapons as possessions (that you can buy, find, or drop), and I presume the skill is what lets you be effective with a given weapon.  But the way I look at it, the weapons and medicine don't have skills, the character does.  In fact, I strongly suspect that the Character is the central figure in your data design.

Here are three data objects that stand out to me from your design so far:

```<code>Character:
    Life (a value: e.g. 12)
    Strength (a value: e.g. double, triple, quadruple)
    Skills (list or set of weapon-skills, healing-skills)
    Possessions (list of weapons, armor and other possessions)
    WornArmor (maybe only wear one you possess at a time?)
    WieldedWeapon (one or two of your posessions)

Skill:
    Skill-Type (healing, manufacture, or weapon)
    RelevantWeapon (for this skill)

Weapon:
    IsOneHanded (boolean)
    IsBow (boolean)
</code>```

Now a character can have weapons and skills, but for a really good attack, they need a skill specific to the weapon they are using.  In any case, there are one-to-many relationships here (one character can have many skills).  But I'm not seeing trees yet.

Take a pad of paper and on the first page put the character in the middle of the page and list the 5-10 most important game-world objects around it.  Figure out what data is merely an attribute of another object (such as Life and Strength being inseparable parts of the character)  and what the most important relationships are between the objects, without thinking about trees or text-fields or combo-boxes.  Draw lines between objects to represent relationships  Then figure out which relationships are 1:1, which are 1:many, and which are many:many and label them.  There may be "has-a" and "is-a" and other kinds of relationships as well.

You may decide you need separate representations for a WeaponSkill vs. HealingSkill vs. ManufactureSkill.  Or you may decide they are so similar that they belong in one Skill table (in my example above) with a field determining which type of skill it is.

It's a good sign that you are not content with your attempts so far - it means you are willing to consider many possibilities before picking one.  The more sketches you consider, the better your final design will be.  Eventually, the best one will become your data diagram.  When that is fairly well settled, you can return to thinking about "combo-boxes" or "text fields", but I'd leave the UI decisions to the end.

Rather than look at JTrees, I would suggest you look into the topics of Data Structures, Database Design, and maybe Data Modeling.  EDIT-> Or better yet entity-relationship mapping diagrams as David Kaczynski suggested! <-EDIT  If you get the data design right, then the Java and the UI will flow from it obviously and naturally.  But if you get it wrong, than no amount of Java-kung-fu or UI-beauty will fix it.

Good luck!

Body:
I don't think JTree is the right representation for the problem you are trying to solve.  I looked at your web site, and I see lists of stuff.  This is a great start, but I think there is an underlying data design that you may have, but I am not seeing.

Life and Strength look like character attributes to me.  Double, Triple, and Quadruple look like values for the Strength attribute.  Then I see skills divided into Weapon and Medical.  I think of weapons as possessions (that you can buy, find, or drop), and I presume the skill is what lets you be effective with a given weapon.  But the way I look at it, the weapons and medicine don't have skills, the character does.  In fact, I strongly suspect that the Character is the central figure in your data design.

Here are three data objects that stand out to me from your design so far:

Character:
    Life (a value: e.g. 12)
    Strength (a value: e.g. double, triple, quadruple)
    Skills (list or set of weapon-skills, healing-skills)
    Possessions (list of weapons, armor and other possessions)
    WornArmor (maybe only wear one you possess at a time?)
    WieldedWeapon (one or two of your posessions)

Skill:
    Skill-Type (healing, manufacture, or weapon)
    RelevantWeapon (for this skill)

Weapon:
    IsOneHanded (boolean)
    IsBow (boolean)

Now a character can have weapons and skills, but for a really good attack, they need a skill specific to the weapon they are using.  In any case, there are one-to-many relationships here (one character can have many skills).  But I'm not seeing trees yet.

Take a pad of paper and on the first page put the character in the middle of the page and list the 5-10 most important game-world objects around it.  Figure out what data is merely an attribute of another object (such as Life and Strength being inseparable parts of the character)  and what the most important relationships are between the objects, without thinking about trees or text-fields or combo-boxes.  Draw lines between objects to represent relationships  Then figure out which relationships are 1:1, which are 1:many, and which are many:many and label them.  There may be "has-a" and "is-a" and other kinds of relationships as well.

You may decide you need separate representations for a WeaponSkill vs. HealingSkill vs. ManufactureSkill.  Or you may decide they are so similar that they belong in one Skill table (in my example above) with a field determining which type of skill it is.

It's a good sign that you are not content with your attempts so far - it means you are willing to consider many possibilities before picking one.  The more sketches you consider, the better your final design will be.  Eventually, the best one will become your data diagram.  When that is fairly well settled, you can return to thinking about "combo-boxes" or "text fields", but I'd leave the UI decisions to the end.

Rather than look at JTrees, I would suggest you look into the topics of Data Structures, Database Design, and maybe Data Modeling.  EDIT-> Or better yet entity-relationship mapping diagrams as David Kaczynski suggested! <-EDIT  If you get the data design right, then the Java and the UI will flow from it obviously and naturally.  But if you get it wrong, than no amount of Java-kung-fu or UI-beauty will fix it.

Good luck!


问:
Are costs part of the requirements?
I am new to requirements analysis and have a simple questions: Would you include the budget in the requirements, if e. g. the departments budget for running costs is 10k a year. </p>

答:
I disagree, cost should, no MUST be represented in some form.

Projected operating costs have an enormous impacts on a project.  Making abstraction of this until the very end (when the product is actually sold) is an enourmous mistake.

Cost may not be a direct requirement but it should still be a driving force when writing these requirements.

I have seen a project completely derailed simply because the cost of configuring the system were never given an iota though space.  It`s not that the configurability was not designed, it was, and it did follow all the technical requirements to the letter.  Once all delivired  they calculated all the costs to present for a bid and they were 5 times higher than anyone else in the bidding contest.  Had the configuration costs been integrated in a requirement from the start this would have never happened.

Costs are much more than dollar value stuck on a shrink wrapped box.  Software has to be maintained, updated, configured, installed etc.  Cost can play a major role in key decisions made throughout the software design and production.  Thus they should be known and parametrized as all other constraints affecting design... through requirements.

Title: Are costs part of the requirements?


问:
Why are many programmers moving their code to github?
For the past 6 months or more, I've been seeing many codes hosted at sourceforge.net as well as other hosting sites "Move to GitHub". A mere Google Search with the phrase "Moved to Github" returns several results containing the text moved to github. This is very confusing for me, and I'm wondering, why exactly are people moving? Does it mean that GitHub is better or is there some special advantage I'm not seeing?</p>

答: One additional reason that may be drawing additional developers to GitHub is that developer tools are starting to embrace git, and platforms like Eclipse now have Git support built in out of the box (applies to the packages for Java, C++ Developers, etc), making it take less steps to get your project uploaded to GitHub.</p>


问:
Are UML class diagrams adequate to design JavaScript systems?
Given that UML is oriented towards a more classic approach to object orientation, is it still usable in a reliable way to design JavaScript systems?

One specific problem that I can see is that class diagrams are, in fact, a structural view of the system, and JavaScript is more behaviour driven, how can you deal with it?

Please keep in mind that I'm not talking about the real world domain here; it's a model for the solution that I'm trying to achieve.

答:
Your answer is hidden in your question:

One specific problem that I can see is that class diagrams are, in fact, a structural view of the system, and javascript is more behaviour driven, how can you deal with it?

Look at  BDD (Behavior-driven development) techniques and choose tools that suit your design needs.

Related discussion that you may find useful to look - How to write stories / scenarios in BDD. And a very comprehensive article from Code magazine - Behavior-Driven Development

ps: In general, UML represent general types of behavior, however it can still be used to model your design with right set of selected category (like a sequence diagram). I would reference the Wikipedia and find the right UML diagram category to use.


答:
It sounds like you're asking two different things

Can UML be utilized to depict javascript systems?

Can class diagrams be utilized to depict javascript systems?

Keep in mind that UML includes many types of diagrams, specifically a branch of behavior diagrams, including sequence and use case diagrams.  Such diagrams specifically address your concern of modeling javascript as a behavior driven language.

It is quite possible that a javascript system is not using object-oriented design.  In such a case, class diagrams would probably not be appropriate, as you pointed out.  However, since javascript does support object-oriented design, it is possible for class diagrams to effectively depict a system using javascript.  It really depends on how the javascript is being used.

Title: Are UML class diagrams adequate to design JavaScript systems?

Body:
Given that UML is oriented towards a more classic approach to object orientation, is it still usable in a reliable way to design JavaScript systems?

One specific problem that I can see is that class diagrams are, in fact, a structural view of the system, and JavaScript is more behaviour driven, how can you deal with it?

Please keep in mind that I'm not talking about the real world domain here; it's a model for the solution that I'm trying to achieve.


答: There are behavior models, also, in UML that you can use to depict the behavior of the system like Sequence Diagrams or State Chart Diagram</p>


问:
HTML5 and gaming practices
I am trying to build an app with HTML5.

Is there a certain syntax to follow when making objects for games?
Anyone tried that and what are good practices to follow?

答:
Basically there are two main options:
a) using canvas and raycasting b) using game engine to achieve the 3D effect in HTML5.

Have a look at the following cool tutorials and posts:

Creating pseudo 3D games with HTML 5 canvas and raycasting

How to Create an HTML5 3D Engine

Canvas tutorials

HTML5 ROCKS - POSTS & TUTORIALS

Title: HTML5 and gaming practices


问:
A question on nature of generated assembly in C++ and code Algebra
I wrote this code:

```<code>#include <iostream>
int main()
{
    int a;
    std::cin >> a;
    if(a*a== 3){
        std::cout << a;
    }
    return 0;
}
</code>```

On MSVC I turned ON all optimization flags. I expected that since a*a can never be 3, so compiler should not generate code for the section:

```<code>if(a*a== 3){
    std::cout << a;
}
</code>```

However it generated code for the section. I did not check GCC or LLVM/CLang.

What are the limits of expectation from a C++ compiler in these scenarios?

答:
I think compiler optimization normally reduces (sub)expressions that depend on constant values only.

If an expression contains variables whose value is bound at run-time, only some basic properties can be checked, e.g. when comparing an unsigned integer with 0, like this:

```<code>unsigned int c;

...

if (c < 0)
{
   ...
}
</code>```

On the other hand, I do not think that it makes sense (or that it is even possible) for a compiler to try and investigate more complex properties of an expression that are valid for all possible inputs and optimize based on that. What to do for example with:

```<code>unsigned int a, b, c, n;

std::cin >> a;
std::cin >> b;
std::cin >> c;
std::cin >> n;

if (n > 2 && pow(a, n) + pow(b, n) == pow(c, n))
{
    std::cout << "OK";
}
</code>```

Apart from possible computation errors due to rounding or overflow the program will never execute the body of the if block(see this wikipedia article for some background), but how should a compiler be able to determine this?

Proving (let alone discovering) theorems about mathematical expression is too complex (or even not computable in certain cases) so it cannot be used as a compiler optimization technique.

Body:
I think compiler optimization normally reduces (sub)expressions that depend on constant values only.

If an expression contains variables whose value is bound at run-time, only some basic properties can be checked, e.g. when comparing an unsigned integer with 0, like this:

unsigned int c;

...

if (c < 0)
{
   ...
}

On the other hand, I do not think that it makes sense (or that it is even possible) for a compiler to try and investigate more complex properties of an expression that are valid for all possible inputs and optimize based on that. What to do for example with:

unsigned int a, b, c, n;

std::cin >> a;
std::cin >> b;
std::cin >> c;
std::cin >> n;

if (n > 2 && pow(a, n) + pow(b, n) == pow(c, n))
{
    std::cout << "OK";
}

Apart from possible computation errors due to rounding or overflow the program will never execute the body of the if block(see this wikipedia article for some background), but how should a compiler be able to determine this?

Proving (let alone discovering) theorems about mathematical expression is too complex (or even not computable in certain cases) so it cannot be used as a compiler optimization technique.


答:
IMHO a more pragmatic approach is not to think in "classes" when decoupling parts of your system for better testability, but to think in "components" - bigger functional units with a well-defined task which may be composed of one or more classes. If one component needs the service of another one, then it should not use it directly, but only via an interface. How this interface looks like can be very component dependent, it may be utilize the language definition of an interface in your programming language, it may be just a function or call-back, it may use streams or some kind of "data objects".

To my experience, it is also a good idea for testability to design your component interfaces in a way you can provide all input and output in-memory. For example, say you have component A which uses objects of your database as input and output, and component B, which relies on the output of A, and utilizes the database, too. Then provide a way that A produces the data objects just in-memory, and a way that B can accept those objects from A in-memory too, without any interaction with a database. That makes writing automatic tests for A and B a hell lot of easier (and the tests running much faster).