答:
You will need to edit pages (that probably have a .aspx extension) that have both html and some server side code mixed together but you probably won't need to change the server side piece much, maybe just where it appears.  These are plain text files that you can edit with any editor, just like .html files.  You may want to use an IDE or you may find it easier to just edit the pages with a basic editor for your OS platform (Notepad, emacs, textmate, vi, etc).

For example:

```<code><html>
<head>
<title>The current time</title>
</head>
<body>
The server's current time:<br />
<%
Response.Write Now()
%>
</body>
</html>
</code>```

The HTML you should be comfortable with.  The stuff within the <% %>'s is the server side code.  In this case you can guess from the surrounding html code that Response.Write Now() puts out the current time.

How easy it will be overall will depend on the complexity of the site. A site with 5 pages that are all public (no login) is going to be a different case from one with role based logins and 150 different pages.  If the server code just outputs a few variables that's one thing.  If you have complex pages with master-detail records and lots of Javascript and AJAX, that will be harder as the code may be more mixed in, especially in things like iterators for collections of records.

You will want to 'see' what the pages look like you will need to either run a local server or have a test server that you can push changes to to see their effect.

Much much more at: http://en.wikipedia.org/wiki/Active_Server_Pages

Title: How to edit the HTML of an ASP.net site?

Body:
Assume that I'm a front-end developer (HTML, CSS)

And some one who got their website built using ASP.NET came to me and asked for a new design and I don't know about ASP.NET.

Then, how can I change the design of their website without affecting their code?

Do I have to learn a little bit of server side languages to be able to change to the look of sites without affecting the original server code?

Body:
You will need to edit pages (that probably have a .aspx extension) that have both html and some server side code mixed together but you probably won't need to change the server side piece much, maybe just where it appears.  These are plain text files that you can edit with any editor, just like .html files.  You may want to use an IDE or you may find it easier to just edit the pages with a basic editor for your OS platform (Notepad, emacs, textmate, vi, etc).

For example:

<html>
<head>
<title>The current time</title>
</head>
<body>
The server's current time:<br />
<%
Response.Write Now()
%>
</body>
</html>

The HTML you should be comfortable with.  The stuff within the <% %>'s is the server side code.  In this case you can guess from the surrounding html code that Response.Write Now() puts out the current time.

How easy it will be overall will depend on the complexity of the site. A site with 5 pages that are all public (no login) is going to be a different case from one with role based logins and 150 different pages.  If the server code just outputs a few variables that's one thing.  If you have complex pages with master-detail records and lots of Javascript and AJAX, that will be harder as the code may be more mixed in, especially in things like iterators for collections of records.

You will want to 'see' what the pages look like you will need to either run a local server or have a test server that you can push changes to to see their effect.

Much much more at: http://en.wikipedia.org/wiki/Active_Server_Pages


问:
Mutable and Immutable version of Collection implementations or both stuffed into one via .makeImmutable()
I am currently working on a collection implementation in JavaScript. I need a mutable and an immutable version of that. So what I thought of first was something like:

Collection

MutableCollection extends Collection

ImmutableCollection extends Collection.

My main issue with this is that if I want to implement more specific collections like List or Set, they could still inherit from Collection while their Mutable/Immutable implementations could not inherit from MutableCollection / ImmutableCollection.

So this made me think whether having all three, Collection, MutableCollection and ImmutableCollection would actually bring any significant benefit.

An alternative approach which came to me would be to only have Collection and then have a Collection.prototype.makeImmutable or freeze there. I would then also introduce a Collection.requireMutableInstance( collectionInstance ) which can be used in functions explicitly requiring a mutable collection.

Here are my main concerns about putting everything into just Collection:

The prototype definition is getting much bigger compared to defineing a MutableCollection prototype as well which would then hold the code of all the operations for alteration. I guess I could solve this by just defining a second file anyhow which would then just extend the basic Collection definition with those additional operations and the makeImmutable operation.

Documentation of those function signatures that actually care about mutable vs. immutable and not just require the basic collection would look less pretty.

Take:

```<code>/**
 * @param {MutableCollection} collection
/*
function messAroundWithSomeCollection( collection ) { /* ... */ }
</code>```

vs.

```<code>/**
 * @param {Collection} collection A collection not yet made immutable.
/*
function messAroundWithSomeCollection( collection ) { /* ... */ }
</code>```

What would be the more natural way of doing this in JavaScript? Especially without having interfaces I can check against and considering the flatter chains of inheritance if I would also implement a Set and Map collection, the everything-in-one approach seems more intuitive to me.

答:
The "class hierarchy" that you mention depends a lot on what you put in Collection. For an immutable list what you usually need is a way of iterating through values: length, forEach, map, find, etc.

So what has the ImmutableCollection interface that is not already part of Collection?
Another possible hierarchy could be:

Iterable: length, forEach

MutableCollection: implements Iterable, but adds mutators add, remove

About how to convert a mutable collection into immutable, use a decorator:

```<code>    new ImmutableView(mutableCollection)
</code>```

Where ImmutableView implements Iterable but doesn't expose any mutator.
That's the approach used by most collection APIs: Java, Scala, Dart. (Actually Java implementation is broken in the sense that Collection already have mutators, so an Immutable collection is as collection that doesn't follow the substitution principle: add/remove throws exceptions so semantically doesn't implement the interface)

About the Collection.requireMutable. Why do you want to do that? JavaScript is not statically typed, so what you want to do is to emulate some sort of type checking.
If that really bothers you, switch to a language like TypeScript or Dart.
If not, assume that you receive a mutable collection and don't do any additional check.
Everything will be fine as long you:

Do unit tests. TDD is the best companion for big systems based on dynamic languages

Follow the Liskov substitution principle. Even if JavaScript doesn't have static typechecking, is good exercise to think about it. A quick rule of thumb, if your code has some if (x instanceof Y) conditionals.. you are not following the substitution principle. It means that you are not taking advantage of polymorphism.

ContentLicense: CC BY-SA 3.0

Body:
The "class hierarchy" that you mention depends a lot on what you put in Collection. For an immutable list what you usually need is a way of iterating through values: length, forEach, map, find, etc.

So what has the ImmutableCollection interface that is not already part of Collection?
Another possible hierarchy could be:

Iterable: length, forEach

MutableCollection: implements Iterable, but adds mutators add, remove

About how to convert a mutable collection into immutable, use a decorator:

    new ImmutableView(mutableCollection)

Where ImmutableView implements Iterable but doesn't expose any mutator.
That's the approach used by most collection APIs: Java, Scala, Dart. (Actually Java implementation is broken in the sense that Collection already have mutators, so an Immutable collection is as collection that doesn't follow the substitution principle: add/remove throws exceptions so semantically doesn't implement the interface)

About the Collection.requireMutable. Why do you want to do that? JavaScript is not statically typed, so what you want to do is to emulate some sort of type checking.
If that really bothers you, switch to a language like TypeScript or Dart.
If not, assume that you receive a mutable collection and don't do any additional check.
Everything will be fine as long you:

Do unit tests. TDD is the best companion for big systems based on dynamic languages

Follow the Liskov substitution principle. Even if JavaScript doesn't have static typechecking, is good exercise to think about it. A quick rule of thumb, if your code has some if (x instanceof Y) conditionals.. you are not following the substitution principle. It means that you are not taking advantage of polymorphism.


问:
A question about storing passwords
I'm creating a program (in C++) that will password protects its user's database (.dat) file. I'm confused on where to store the password? In the user's database file or somewhere else.

I'm new to this concept. I don't know where a program should store the hashed password. I've been thinking for this from a long time.

I have a question too. If a program stores hashed password in the database file (along with users data) is it possible for an attacker to modify the hash inside the file to some common hash like the hash of the text 'password' so that the password becomes 'password'?

Edit: Okay! I've somewhat understood the password storing concept. This is what I've understood:

Get the password from the user

Hash it (I will use SHA-512)

Store the hash in the database file

Done

Probably, I didn't understand the symmetric hash concept. Please explain me in an easy way. And the question I have is... I'll better explain it with an example.

Assume this is user's file's content

```<code>thisismydatabasefile
</code>```

User decides to add a password. He types in the password and we hash it. The generated hash is somerandomhash. We encrypt the file with somerandomhash as the password and the hash is included in the encrypted file. So now the file content is

```<code>encryptedfilesomerandomhash
</code>```

Imagine the attacker got the encrypted database file. He knows that the hash of the password is "somerandomhash". He now modifies the password hash 'somerandomhash' to something common like 'somehashthatheknows'. So what is a better way to store a password.

For ease, how do programs like zip, 7z, rar etc store passwords inside a archive file?

答:
You correctly identified that storing the hash anywhere on the disk makes the password vulnerable to attacks such as breaching file access control, known cypher-text attacks, or chosen cypher-text attacks.

Security Solution: Do not store a hashed password on the disk.

Since your database is just a file we can use the general way to securely password protect a file on disk.

Algorithm To Securely Password Protect A File:

Have the user input a password at runtime for the file. (database in your case)

Hash the password. (I'd use SHA-256)

Use the hash to derive a symmetric 256-bit key. (I'd use hash directly as the key)

Use the 256-bit key to encrypt/decrypt the database file on the disk. (I'd use the AES algorithm)

Major Pro:
Database encryption key is generated at run-time and never stored on the disk.

Minor Con: Encryption and key derivation becomes implementation specific and laborous to implement.

You get to decide whether the required security for the application is worth the time to implement the security protocols correctly.

Title: A question about storing passwords


问:
Build status reporting on javascript project
I have a javascript project which uses Grunt and several plug-ins such as:

jshint

qunit

requirejs optimizer

Not all of the developers run the grunt tasks locally (e.g. jshint, qunit), so they might not know if code they committed has issues. It's easy enough to set up a grunt watch task, but emailing the team upon error/warning has been less obvious than I expected.

I was expecting to find something like grunt-contrib-emailstatus for emailing a nicely-formatted status, but so far have not come across this. Did I miss it?

If not, what's the recommended practice here? In the past I've seen things like Cruise Control, Jenkins, or Hudson handle the build status reporting, but it seems like too big a hammer for this nail. And on the other hand, trying to use crontab to email status seems too small.

答:
What I did in my team is:

We use git, so I've setup a git commit hook. So each time that you commit Grunt runs jshint. If it fails you cannot commit.

Good: A lot of times I forgot to run jshint by hand. So a commit failure is the best reminder.

Bad: Commit hook means: commit to your git repo (not receiving a push on the origin). So you need to setup the commit hook locally (I've created a grunt task for that). Because of that the effectiveness of the approach depends on each developer honesty (also you can force the commit without running the hooks). Another con: If you use some Git UI, you need to properly setup the PATH so the program can run the commit hook without errors. But setting up the PATH for UI in MacOSX is not so easy (lots of changes in that area between MacOSX versions)

We use Jenkins. So the build fails if jshint or the unit tests fails. Yes it's a "big hammer", but these tools are designed for that kind of continuos integration tasks. You can use them for other kind of stuff like creating your production bundle, or doing some functional tests using real web browsers. For example we use Jenkins hosted on Cloudbees and we trigger some functional tests based on SauceLabs.

Also it's possible to setup a server side commit hook. I couldn't do that since we use Github and we don't control the git server (Github offers that functionality by connecting third party apps to your repo, like Travis CI).

But if you control your git repo, and you don't want to use a big CI tool, you can setup a post-receive hook that (http://git-scm.com/book/en/Customizing-Git-Git-Hooks) that fires the verification on background and sends the email (basically you are writing a home-brew CI tool in that case ;) )


问:
How to edit the HTML of an ASP.net site?
Assume that I'm a front-end developer (HTML, CSS)

And some one who got their website built using ASP.NET came to me and asked for a new design and I don't know about ASP.NET.

Then, how can I change the design of their website without affecting their code?

Do I have to learn a little bit of server side languages to be able to change to the look of sites without affecting the original server code?

答:
I think the idea is all about differentiating between HTML, CSS and server side code. So, anything not HTML or CSS could be a server-side code. However, don't forget JavaScript code as well.

Quoting from Michael Durrant "..this case you can guess from the surrounding html code that Response.Write Now() puts out the current time". It is clear that you can sometimes know even the output of server side code depending on the surrounding HTML.

In short, try to get a page where server-side and HTML are mixed and try to change the HTML, CSS and see the result. I'm sure you'll learn in this way.


问:
What characteristics or features make code maintainable?
I used to think I knew what this was, until I really started thinking about it... "maintainable"... what exactly makes code maintainable?

To me, if code must be maintainable that means we can expect to revisit the code to make some sort of change to it in the future. Code is always "changeable" no matter what state it is in. So does this mean code needs to be easy to change? However, if our code was scalable/extensible, there would be no need to directly change it, because it will "change" (adapt) for free and automatically.

I've also seen code maintainability used interchangeably with coding standards. Using a consistent coding pattern or style, does this really make code more maintainable? More readable and more consistent? Sure, but how does this improve the maintainability?

The more I try to think into this, the more confused I get. Anyone have a proper explanation?

答:
I have defined maintainability as:  a measure of the effort required to change the functionality of application software.  A measure of ‘effort’ must include time, resources and expertise.

In general any software development manager is familiar with this definition of ‘effort’ as it applies to creating software.  The term ‘change the functionality’ applies to both enhancements as well as bug fixes.   It might also be said that maintainable code is designed to be leveraged.

It does take some effort to create maintainable software.  For what it is worth, I recently started a blog on the subject.

http://rdq-software.blogspot.com/


问:
When does it become overkill?
First off, I apologize cause I don't know how to make a community thread; so someone help me out please.

As a developer, across many platforms, technologies and even on an infrastructure level; I always find myself asking, when am I doing TOO much?!?

It's been a never ending learning process, since I started. One (1) thing I learned is that requirements are barely valid for an extended period of time, and as such a little foresight may go a long way.

But where is the balance, and how do you know when you're losing time, not gaining it?!

答:
Your question is quite open-ended, so I'll interpret it as "doing too much on one part of the project":

For me, it's easy to spend too much time on something which doesn't really provide much gain for the customer. Often, it is the tiny things such as "Well, it works, but not entirely like I want it too" where the customer probably wouldn't care if it worked this way or another.

When that happens, I should stop it and spent time on things which are more important. It's better that the product works as a whole than not but you have these smaller parts which work perfectly.

Writing tracer code (from Code Complete) is probably a good idea of avoiding this: You start your project by writing code which connects the whole code - from the GUI (or near to it) all the way to the backend and then back. That way you always have something that works and you don't spent time perfecting the little things until the whole thing runs.

But still, it is a matter of discipline and prioritizing.

ContentLicense: CC BY-SA 2.5

Title: When does it become overkill?


问:
Level of detail of a user story
I am about to start User story sessions in my team. It's quite new for them and I am also wrestling with certain things. For the current project we have some well worked out wireframes.

I read a lot about the way of writing user stories. What the template should be like and about different aids like Invest

The plan is to turn them around in user stories. Lets say I have a screen where a user could edit an order. There is a lot of detail on that screen. Now when creating a user story of this story. Will it suffice to say:

As an Admin I can edit a purchase order so that mistakes typed by the
user can be enhanced.

Or should i specify each detail like:

As an Admin I can resend an invoice to the customer, so he can get a copy of his lost one.

As an Admin I can review the customer order so he has detailed information about each purchase

As an admin I can remove items forma on order so that in case the customer made a mistake I can remove Items.

And how about the acceptance criteria. How should the be defined for a user story as such. Where do I define which fields need to be shown on an order detail page? Can this be part of the acceptance criteria?

答:
There is no "prescribed" way to do stories in scrum, so there is no straight answer to your question, however I can give you some general advise based on experience:

If your team is not experienced in scrum, make the stories as small as possible. In fact, if you can make them small enough, you can substitute that for story point estimation without losing much predictability.

Put as little as possible in the story. Avoid designing software in stories, include only what matters to the user. Are the exact fields absolutely necessary? You better make sure they are developed: use acceptance tests. Are the fields not strictly necessary as long as a certain operation can succeed? Put the success of that operation as acceptance, instead of the fields.

Make sure your product owner is available during the sprint to answer question and provide details. Don't fall in the trap of having the PO only interact at the planning meeting or using the stories as a message board to the team. The PO is part of the team and must be in the team during the sprint.

Hope this gets you started in the right direction! Good luck!

Title: Level of detail of a user story


问:
Issue with scrum adaptation by team
I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer.

People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not.

In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?

答:
I think the problem is that the stories are "assigned". The team should decide who does what, and the team should be co-responsible for the success.

Should the junior developers take more senior tasks? Sometimes, yes, otherwise how will they ever grow? They need to convince the more senior devs to let them try and provide a safety net.

I suspect that once the team is empowered with the distribution of work, they will change their attitude and point of view. At the moment they seem to complain because they do not feel personally responsible.

Title: Issue with scrum adaptation by team


问:
TFS Branching Advice
I am new to Branching and Merging but I have been tasked with making future development on an application possible while still allowing bug fixes to production. Usually I am the only developer on the application unless I am on leave.

I have watched a Pluralsight video on Branching and done some forum/stack reading. I was hoping someone could take a look at my solution proposal and critique. I am concerned I will cause more problems than solutions if I get this wrong

As of Version 1.1.0.0 I have introduced a branching system for future development. Version 1.1.0.0 is our production branch. No changes should appear here except bug fixes.
  Version 1.2.0.0 is the next version and our development branch.

After completing a development, the development branch will merge to the Application (trunk). The application will be deployed for testing. After sign off the development branch becomes production, the previous version branch will be removed. A new branch will be created for the next version.

For bug fixing, the bugs are fixed against the production branch and merged to the application so when the development branch merges down it also obtains those fixes.

答:
Sounds like 'scenario 2: branch for release" as described by Microsoft's guides.

Its probably the most commonly used branching strategy when using TFS, you have a Main branch from which you make a Dev branch for development, when you're read to merge back, you merge onto Main, perform some testing and then either release from the Main branch, or more commonly, take the Main onto a Release branch so you can make changes to an individual release without having to worry about further updates that have been merged onto Main getting in the way.

Some people never make bug fixes directly on the production branch, they branch from it, make the bug fixes and then merge them back when they've been tested and verified. It makes things easier if you decide not to go with the bug fixes, or have to revert them later as each bug fix release will be a single 'merge' revision onto your release branch rather than a heap of commits.

So, in summary: I would go with 3 branches, one for dev, one for QA (which is also the main line) and another branch for releases. you can tag each release revision if you know you do not have to maintain old versions, but if you do then that Release branch should be a release branch per release, or major version, of your product.

With git and similar systems, you tend to see more of a feature or team branch strategy as merging is a lot easier than on TFS. With something like svn, you tend to see both types.

Title: TFS Branching Advice


答:
You leverage the OS features for password storage. For example, on Windows you'd install your program with a dedicated user account and it would know the password for itself, you'd then use it to decrypt your database file. Any attacker would have to then run the program as that user, or if they'd stolen the DB file then they would not have access to the password anywhere - the program itself doesn't have access to it. Password management then becomes an admin task associated with user accounts, not something unique to your program.

Brute force decryption obviously would still be possible attack vectors, but for that to work they'd have to steal the DB file and hack it "offline".

As an example, think of how webservers give access to a DB that requires a password without letting anyone else have access. The password is stored, in plain text usually, in a text file on disk. But that file is not accessible to anyone other than the webserver using what file protection the OS provides.

Title: A question about storing passwords

Body:
I'm creating a program (in C++) that will password protects its user's database (.dat) file. I'm confused on where to store the password? In the user's database file or somewhere else.

I'm new to this concept. I don't know where a program should store the hashed password. I've been thinking for this from a long time.

I have a question too. If a program stores hashed password in the database file (along with users data) is it possible for an attacker to modify the hash inside the file to some common hash like the hash of the text 'password' so that the password becomes 'password'?

Edit: Okay! I've somewhat understood the password storing concept. This is what I've understood:

Get the password from the user

Hash it (I will use SHA-512)

Store the hash in the database file

Done

Probably, I didn't understand the symmetric hash concept. Please explain me in an easy way. And the question I have is... I'll better explain it with an example.

Assume this is user's file's content

```<code>thisismydatabasefile
</code>```

User decides to add a password. He types in the password and we hash it. The generated hash is somerandomhash. We encrypt the file with somerandomhash as the password and the hash is included in the encrypted file. So now the file content is

```<code>encryptedfilesomerandomhash
</code>```

Imagine the attacker got the encrypted database file. He knows that the hash of the password is "somerandomhash". He now modifies the password hash 'somerandomhash' to something common like 'somehashthatheknows'. So what is a better way to store a password.

For ease, how do programs like zip, 7z, rar etc store passwords inside a archive file?


问:
How to educate business managers on the complexity of adding new features?
We maintain a web application for a client who demands that new features be added at a breakneck pace. We've done our best to keep up with their demands, and as a result the code base has grown exponentially. There are now so many modules, subsystems, controllers, class libraries, unit tests, APIs, etc. that it's starting to take more time to work through all of the complexity each time we add a new feature. We've also had to pull additional people in on the project to take over things like QA and staging, so the lead developers can focus on developing.

Unfortunately, the client is becoming angry that the cost for each new feature is going up. They seem to expect that we can add new features ad infinitum and the cost of each feature will remain linear.

I have repeatedly tried to explain to them that it doesn't work that way - that the code base expands in a fractal manner as all these features are added. I've explained that the best way to keep the cost down is to be judicious about which new features are really needed. But, they either don't understand, or they think I'm bullshitting them. They just sort of roll their eyes and get angry. They're all completely non-technical, and have no idea what does into writing software.

Is there a way that I can explain this using business language, that might help them understand better? Are there any visualizations out there, that illustrate the growth of a code base over time? Any other suggestions on dealing with this client?

答:
A few pieces of advice. First, use an analogy - pretend you were implementing this without computers, such as doing it by mail (not E-mail). As you add features, visualize the form customers fill out getting more and more complex. Think about the increased breadth of skills required by staff and the number of staff required to fulfill each function. Talk about the increases cost to manage the increased staff, such as management, training, HR, payroll and so on. Computers can do this faster but most other aspects still apply.

Second, gather code and QA metrics such as the number of bugs found, code complexity, automated test coverage, time to develop, time refactoring (if any) and so on. If you have QA, capture the number of tests required for a full regression and the time needed to run them all. Support increased costs with facts makes them much harder to argue with. Even a simple diagram showing the number of and interdependencies between different modules may help.

Third, gather analytics about how customers use your software. If you create a feature no one uses, being able to point to an automatically generated, auditable source of truth can help you prioritize work (at worst) or avoid unnecessary features (at best).

Fourth, get an outside opinion. This may or may not be viable depending on the company size and structure but pull someone senior in from elsewhere and get an unbiased opinion. They will likely suggest a mix of improvements to development practices (a win for you so you can get time for refactoring or increasing your output) and better prioritization of features (also a win for you so you have fewer, better features). Alternatively, suggest relevant reading like "The Lean Startup" by Eric Ries.

Last but not least, try to understand the business case. Why do you think the business is driving these new features as hard as they are? Are they trying to keep up with competitors? Are they under pressure from their management to deliver? Perhaps the people driving you are the symptom and not the cause. An "us and them" mentality is counterproductive. It may be extremely difficult at first but this will help you in the long run.


问:
Should I include test runner module as a dependency in my module?
My module has no dependency on its own but for running tests you need to install jasmine-node module. Should I include that module as a dependency?

答: Most package management systems have a special way of specifying dependencies that are needed only for the development. Python's setuptools has extras_require, Clojure's leiningen has profiles, and npm has devDependencies: see docs.


问:
Date & time - apply current, or 'then' DST?
I'm designing a function that given a UTC timestamp will convert it to the local time.

The question I have, should the current times DST settings be applied to the conversion, or the timestamps DST settings?

If going with the former, current DST setting applied to timestamp - it would mean 4pm that was recorded with DST+1 would be 3pm with DST+0 and 4pm with DST+0, depending on the time of the year you checked the date at.

If going with the latter, the timestamps DST setting would be applied to it - so 4pm recorded with DST+1 will always say 4pm, no matter what time of the year you've checked it at.

Which is more preferrable in practice?

答:
Use the DST settings applicable to the timestamp.  This will apply the correct conversion rules.  For example if I use the current DST status a local time in January would be incorrectly converted, as I am currently in DST and January uses ST here.

Most languages already have a function or method to do the conversion.  Unless you have strong reasons to write your own, use it.  This code should provide a way to determine if the the timestamp is DST or ST.

Many protocols use a format which includes the offset from UTC, as a suffix.  For example:

```<code>Delivery-date: Sat, 14 Sep 2013 06:47:18 -0400
</code>```

There are a lot of pitfalls in writing your own code:

Rules change from time to time.

Timezone change is often not done at midnight.

Rules can be different for different locations in the same timezone.

Leap seconds may or may not be included in the time stamps.

The Olson Time Zone Database contains an accurate rule set and is frequently updated.

Body:
Use the DST settings applicable to the timestamp.  This will apply the correct conversion rules.  For example if I use the current DST status a local time in January would be incorrectly converted, as I am currently in DST and January uses ST here.

Most languages already have a function or method to do the conversion.  Unless you have strong reasons to write your own, use it.  This code should provide a way to determine if the the timestamp is DST or ST.

Many protocols use a format which includes the offset from UTC, as a suffix.  For example:

Delivery-date: Sat, 14 Sep 2013 06:47:18 -0400

There are a lot of pitfalls in writing your own code:

Rules change from time to time.

Timezone change is often not done at midnight.

Rules can be different for different locations in the same timezone.

Leap seconds may or may not be included in the time stamps.

The Olson Time Zone Database contains an accurate rule set and is frequently updated.


问:
Why is this syntax convention?
It says in the book (APress Ganesh / Sharma) about Java 7:

You create a method named fill() in the Utilities class with this
  declaration:

```<code>public static <T> void fill(List<T> list, T val)
</code>```

You  declare the generic type parameter T in this method. After the
  qualifiers public and static, you put <T> and then followed it by
  return type, method name, and its parameters. This declaration is
  different from generic classes—you give the generic type parameters
  after the class name in generic classes.

But why <T> as in public static <T> ? The syntax looks odd and appears nowhere else in the Java language. What does the <T> mean in this case and why is it used?

答:
it means only the method is generic and allows the class to be not generic (or use a generic parameter not in the class)

for example the Collection toArray method has a parameter, this will allow the type of the array to be different from the type of the collection, (handy when the Collection type is complicated)

the angle brackets is to remain backwards compatible with the existing syntax (pre 1.5), which only used it for the comparison (and it's cheated of from C++ where they faced the same problem concerning compatibility with existing code) ans this way older compilers will choke on exactly that syntax, which will indicate exactly where the problem is

so they deliberately choose the syntax because it was used nowhere else in the language

the location in the declaration before the return type is to not confuse the compiler when a raw type is used (like is public List <T> foo(T t)  a method returning List<T> or a generic method returning a raw List)

the calling syntax Class.<T>foo() is again to avoid confusing the compiler; the < after . can only mean the start of a generic qualifier, while putting it after the method name can be ambiguous:

is foo(MyClass.bar<T,Y>(ab)) calling a single parameter foo using the return type of MyClass.bar<T,Y> or a foo that takes 2 booleans, you need to know whether MyClass.bar is a field or a method

Title: Why is this syntax convention?


问:
There are two types of color mixing: Additive and Subtractive. How about XOR-ive color?
There are two types of color mixing: Additive and Subtractive. http://en.wikipedia.org/wiki/Color_mixing

Is is possible that color mixing model be done in XOR?

答:
Additive and subtractive mixing can be defined in terms of formulas that approximate certain real-world properties (mixing of coloured light, mixing of paint, application of successive coloured filters etc.)

XOR doesn't really make sense in this context, for two reasons:

XOR works with binary values, 1 and 0 (or true and false). It isn't normally defined on continuous values, which is what you need if you are dealing with colour spaces

What real world property are you trying to model? To my knowledge, there is nothing in nature that displays XOR-like colour mixing behaviour.

You could, of course, define an artificial mixing function that exhibits XOR-like behaviour at extreme values (0.0 and 1.0) and does something else in between. You might even get some interesting visual effects. But it's not a standard technique.


答:
Not exactly. Additive and subtractive colour models are based on continuous physical phenomena, while XOR is a discrete operation lacking a real-world optical counterpart.

Subtractive colour models are based on mixing of pigments, which absorb certain frequencies of light and reflect others—red paint, for example, absorbs non-red frequencies from white (full-spectrum) light and thus reflects red hues. Additive colour models are based on mixing of light frequencies, as with a computer monitor.

The key thing to understand, though, is that additive and subtractive don’t refer to addition and subtraction in the algebraic sense, but rather in the frequency-response sense, which is more akin to audio mixing.

Title: There are two types of color mixing: Additive and Subtractive. How about XOR-ive color?

Body:
There are two types of color mixing: Additive and Subtractive. http://en.wikipedia.org/wiki/Color_mixing

Is is possible that color mixing model be done in XOR?


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
Your problem here is that your test tools are crap. You should be able to mock out that object and call your test method without changing it - because while this simple example is really simple and easy to modify, what happens when you have something a lot more complicated.

A lot of people have modified their code to introduce IoC, DI and interface-based classes simply to enable unit testing using the mocking and unit test tools that require these code changes. I don't thin they're a healthy thing, not when you see code that was quite straight-forward and simple turn into a nightmare mess of complex interactions driven entirely by the need to make each and every class method totally decoupled from everything else. And to add insult to injury, we then have many arguments on whether private methods should be unit tested or not! (of course they should, what's the point of unit testing if you only test part of your system) but these arguments are more driven from the point of view that its difficult to test those methods using the existing tools - imagine if your test tool could run tests against a private method as easily as a public one - everyone would be testing them without complaint.

The problem, of course, is in the nature of the test tooling then.

There are better tools available now that could put these design changes to bed forever. Microsoft has Fakes (nee Moles) that allows you to stub concrete objects, including static ones, so you no longer need to change your code to fit the tool. In your case, if you used Fakes, you'd replace the GetTypes call with your own that returned valid and invalid test data - which is pretty important, your suggested change doesn't provide for that at all.

To answer: your colleague is right, but possibly for the wrong reasons. Do not change code to test, change your test tool (or your whole test strategy to have more integration-style unit tests instead of such fine-grained testing).

Martin Fowler has a discussion around this area in his article Mocks aren't Stubs


问:
Problem solving skills and job interviews
Probably few of you are interviewing wannabe programmers. I'm 28, never worked as a programmer, but spent few months learning C and solving problems. I loved it so much that I do it every day just because I can, now and started studying CS at local university.

Now I'd like to try make living from it and am trying some job interview questions I find on the internet. Some are obvious for me, but some scare me and take me long time to find a solution.

When you do job interviews, how long you wait for someone to come up with solution? - - Does freezing for some time on problems that take 5-line code disqualify me as a programmer?

Do you even consider people like me when browsing CV's?

If you do interview someone like me, what do you ask that person?

What are your expectations when you meet interviewee like me?

答:
There is nothing wrong in hiring a person who never worked as a programmer before, and doesn't have a degree yet. If the person is motivated enough and is able to learn by himself, he can become sooner or later a good programmer or developer.

What are the expectations from a candidate with such profile? The same as for any other candidate:

Is the person able to program at all?

What about his communication skills?

Does the person work better alone or in a team? What are the benefits or flaws of the person when working in a team? Is the person more a leader or somebody who will prefer doing what others tell him to do?

Is the person knowledgeable enough in a given technology? In other words, how deep are the skills of this person?

What about other technologies and domains? In other words, how large is the scope of the skills of this person?

Does the person know how to write clean, maintainable code, or has only experience in writing spaghetti code he can't understand himself six months later?

What about the experience with the elementary tools such as bug tracking system and version control?

Of course, for a developer, the list would be much larger than for a programmer, and go much deeper.

As for solving problems, there is nothing wrong in taking time to think. I would rather hire somebody who thinks a bit before starting coding than somebody who jumps to the first idea which gets into his mind, no matter how good or bad it is.


答:
When you do job interviews, how long you wait for someone to come up with solution?

Does freezing for some time on problems that take 5-line code disqualify me as a programmer?

There is little point in waiting for someone to come up with a solution in an interview - you ask something, and then you want to hear how they reason about it. It is comparatively unimportant whether you know an answer or not; this is real life, not school. Virtually everything I'm going to pay you for doing will be new questions, not old ones. Therefore, what counts is how good you are at getting to the solution - whether via web search, communication with colleagues, self-education, etc.

Do you even consider people like me when browsing CV's?

If you do interview someone like me, what do you ask that person?

What are your expectations when you meet interviewee like me?

Let me put it this way:

I loved it so much that I do it every day just because I can, now and started stuying CS at local university

If I could, I would never, ever hire someone as a programmer who can't say this of themselves: that they write programs on their own time because they like doing it. I think that this is a much better predictor of how much value you can bring to us than any certification you could name.

Title: Problem solving skills and job interviews

Body:
Probably few of you are interviewing wannabe programmers. I'm 28, never worked as a programmer, but spent few months learning C and solving problems. I loved it so much that I do it every day just because I can, now and started studying CS at local university.

Now I'd like to try make living from it and am trying some job interview questions I find on the internet. Some are obvious for me, but some scare me and take me long time to find a solution.

When you do job interviews, how long you wait for someone to come up with solution? - - Does freezing for some time on problems that take 5-line code disqualify me as a programmer?

Do you even consider people like me when browsing CV's?

If you do interview someone like me, what do you ask that person?

What are your expectations when you meet interviewee like me?


答:
I have had to hire programmers of both junior and senior level. I have different expectations when I interview people, and I customize each interview to the resume and whatever else I find on the candidate online (relative to his/her job skills).

When I present an applicant with a problem I have a specific goal for it, but there are some common things I look for in all programmers once the problem is theirs.

Never freeze. Even if you have NO IDEA where to go, attack the problem. Do anything to get yourself started in a direction that will lead to a solution. Even if you go in the wrong direction, you'll be somewhere. If you're asked to write code, come up with a signature, review it, modify it. Try to figure out what technique you'll need to use. Write quick pseudo-code. ANYTHING, just start.

Consider each problem fully and in its own context. Write down your assumptions about the problem. Talk to yourself openly while thinking. Don't keep your thoughts to yourself. You are being evaluated on how you solve problems, not the solution you come up with (most of the time), so let the interviewer in on that process.

Don't be afraid to fail at solving the problem. You might not be able to solve it. The interviewer might have expressly set you up with a problem you are not expected to be able to solve simply because he wants to see you reason it out (I pull this one all the time though mostly with senior level programmers).

For a junior position I consider every CV given to me. I look for markers in the resume that hint that the programmer is driven to learn and try. For someone in your position, I want to see a small portfolio with mini projects that show me self-learning. Texts read, classes taken, etc. I truly don't care about the 4 year degree personally, that's HR's problem. A BS in CS will give a candidate a leg up, but it will also place a higher expectation on that candidate.

As for questions I would ask, I'd have to see something from you first. I tailor each interview to the specific candidate because I am more interested in how the candidate learns and grows more than what they've done (for junior developers). I want a determined individual who will attack problems, learn from failures and can formulate solutions.


问:
What is the story behind Java Vulnerabilities?
I always appreciated the Java language. It is known as a very secure platform and many banks use it in their web applications.

I wanted to build a project for my school and I discussed the options with some developers. However, one of them said we should ignore Java ecause of vulnerabilities appreared recently in it.

For this reason I want to make sure, what is the story behind this and does that mean that Java today considered not much secure as it was previously?

答:
Vulnerabilities exist in any large piece of software. Java is not alone in this regard.

Operating systems (Windows, osX, Android, Linux - pretty much all operating system) and many runtimes have had and will have vulnerabilities found.

What you got was the opinion of one person - this doesn't make it universally agreed on. Saying that a language is to be ignored because there were vulnerabilities found (in the language, its' implementation, common libraries and/or runtime) misses the point - every major language has been susceptible to some form of attach (C and buffer overruns, .NET has its own sets of issues etc... etc... etc...).

In short - so there were recent vulnerabilities. Presumeabely they have been patched or fixed in an update. Doesn't mean the language is no longer fit for use.


问:
Inventory / Stock in multiple locations
I am working on a warehouse management system (WMS) that needs to support having stock in multiple locations. Could be in a different building, could be stored in n* places in a building (quick example would be stock, overflow, or fast moving slots all containing a qty of the same item).

Where I am, they have always used one SKU assigned to one bin with paper notes pointing to overflow. Obviously they have grown beyond this and it's causing some serious issues. No one here can help me when I try to get what the best practice should be.

I am having trouble conceptualizing how to setup the structure.

I am thinking ...

Warehouse (virtual or physical) Warehouses can belong to warehouses.

Location - Anything really could be a pallet, box, or just a taped off area on the floor. Locations belong to warehouses.

Rows - can be in locations

Shelves can be in rows

slots(traditionally called a bin here) the smallest unit that can be a location.

Then a SKU could be in any one or many of these locations (except the virtual warehouse - used only from grouping physical locations but allowing a sales order to process them internally as if it shipping from one space).

Locations (are their children) could be given priority. So if a SKU is in 2 locations, the systems knows which slot(bin) to empty first before routing to the next.

I code it so that the structures above can be handled by the warehouse since i don't care physically about them only that the process makes sense and then give them a tool to mark a sort order so that they can determine the best routes through the warehouse with batch picking an order.

I guess I just wanted to get this out of my head and get someone elses eyes on it before I wrote a single line of code.

Does this structure make sense? Is it a best practice? If not what is and if that question is outside the realm of the site could someone point me to it?

答:
Encapsulation is going to be the key for making sure you start with the right structure.

I would have a primary entity for the salable good (widget), of which the SKU is an identity type property.  The salable goods or widgets are your base objects as that's what's being sold.  SKUs can change although it's somewhat rare.

Each widget can have zero or more locations, so I would have a collection of locations within the widget.

Each location is going to have a relative weight representing the availability or location cost for that set of widgets.  I would recommend making the location cost a first class object, and not just a value.  Location cost is a relative term based upon where the caller is located.  If I'm at one site then I want the back-of-store widgets instead of the widgets at another physical location.  At a minimum, you need to hide the implementation of location cost to external callers so you can more easily adapt it in the future.

To support referential integrity, I would make the widget.count() method iterate over all of the locations and count those.  Otherwise you end up doubling the amount of stock keeping you have to do - once for the widget and again for the location.

Title: Inventory / Stock in multiple locations


答:
Here is what that developer is talking about.  See here and here for a list of vulnerabilities in the run-time engine itself.  If you scroll to the bottom of this page and on to the next page you'll find more vulnerabilities that might be relevant, depending on what is in your software stack.

Why?

Well first you have to understand that Java is both a server and a client.  As a client, it tries to run in a carefully sandboxed way where mutually untrusted code can run in the same space.  This is a very hard problem, and it is used in enough "highly interesting targets" that a lot of effort has gone into breaking it.  The result is that most browsers will give you big security alerts before enabling Java.  It is simply too easy for an attacker to send you something which, when run by the JRE, will do Officially Bad Stuff that the security model said it shouldn't do.

People generally do not run untrusted code on a server, so most of that does not apply to you.

Of course there are still vulnerabilities that do apply.  But here we have a more complex question.  Is it better to have vulnerabilities that apply to you, but which you find out about?  Or to not know about vulnerabilities that apply to you?

Java is a high profile target, used in high profile applications.  So a lot of effort goes into finding bugs.  There are a lot of public bugs.  That go into automated attack tools.  That any kid can use, and any decent admin can defend against.  But a penetration tester will have a harder time finding a new one that nobody else has already found.

If you use a less known software stack, there are likely to be similar numbers of bugs, but less effort has been put into finding them.  That means that a random kid with an attack tool that knows a list of bugs is less likely to find something.  But any penetration tester examining your software stack will have a field day finding attacks that you have no way of defending against because you don't know about them.

If you're writing a high profile application (banking software, etc), you have to assume that competent attackers are a fact of life.  Therefore something like Java makes sense there.  If you're a small startup, Java might not make as much sense, but honestly for a startup, how vulnerable your language is is one of your least important problems.  Getting to be big enough that someone would want to attack you would be a Good Problem to have.

And, truth be told, anyone who wants to break into your site will first look around for the obvious SQL injections and the like.  Most of which will be your fault, and not the fault of your vendor.  Really, your language is not going to be your top source of security problems.  Your programming is.  Nor is it your second top source of security problems.  Your misconfiguration of your systems are.

In short, there are a lot of reasons to use or not use Java.  (I personally avoid the language.)  But security isn't a good reason to stay away, despite the large number of known security problems.

Title: What is the story behind Java Vulnerabilities?

Body:
I always appreciated the Java language. It is known as a very secure platform and many banks use it in their web applications.

I wanted to build a project for my school and I discussed the options with some developers. However, one of them said we should ignore Java ecause of vulnerabilities appreared recently in it.

For this reason I want to make sure, what is the story behind this and does that mean that Java today considered not much secure as it was previously?


问:
A question about storing passwords
I'm creating a program (in C++) that will password protects its user's database (.dat) file. I'm confused on where to store the password? In the user's database file or somewhere else.

I'm new to this concept. I don't know where a program should store the hashed password. I've been thinking for this from a long time.

I have a question too. If a program stores hashed password in the database file (along with users data) is it possible for an attacker to modify the hash inside the file to some common hash like the hash of the text 'password' so that the password becomes 'password'?

Edit: Okay! I've somewhat understood the password storing concept. This is what I've understood:

Get the password from the user

Hash it (I will use SHA-512)

Store the hash in the database file

Done

Probably, I didn't understand the symmetric hash concept. Please explain me in an easy way. And the question I have is... I'll better explain it with an example.

Assume this is user's file's content

```<code>thisismydatabasefile
</code>```

User decides to add a password. He types in the password and we hash it. The generated hash is somerandomhash. We encrypt the file with somerandomhash as the password and the hash is included in the encrypted file. So now the file content is

```<code>encryptedfilesomerandomhash
</code>```

Imagine the attacker got the encrypted database file. He knows that the hash of the password is "somerandomhash". He now modifies the password hash 'somerandomhash' to something common like 'somehashthatheknows'. So what is a better way to store a password.

For ease, how do programs like zip, 7z, rar etc store passwords inside a archive file?

答:
Why put the password, in ANY form, on an externally-accessible database on an externally-accessible machine?

The RADIUS protocol was specifically designed to, among other things, allow one protected machine to serve any number of externally-accessible machines, providing authentication and authorization services.  The externally-accessible machine receives the login credential from the user, and forwards it to the RADIUS server.  The RADIUS server knows full well that it is ONLY allowed to handle requests from known machines.  When it receives a properly-authenticated request from an authorized source, it does its thing, and sends back a Yeah Verily/Hell NO! answer, or a more detailed one that says what this user is or is not allowed to do.

Title: A question about storing passwords


答:
From a 1995 interview with Alexander Stepanov in Dr Dobb's Journal: "I returned to generic library development in 1992 when Bill Worley, who was my lab director established an algorithms project with me being its manager. C++ had templates by then. I discovered that Bjarne had done a marvelous job at designing templates. I had participated in several discussions early on at Bell Labs about designing templates and argued rather violently with Bjarne that he should make C++ templates as close to Ada generics as possible. I think that I argued so violently that he decided against that. I realized the importance of having template functions in C++ and not just template classes, as some people believed. I thought, however, that template functions should work like Ada generics, that is, that they should be explicitly instantiated. Bjarne did not listen to me and he designed a template function mechanism where templates are instantiated implicitly using an overloading mechanism. This particular technique became crucial for my work because I discovered that it allowed me to do many things that were not possible in Ada. I view this particular design by Bjarne as a marvelous piece of work and I'm very happy that he didn't follow my advice."

In Ada, a generic must be instantiated, as for example:

```<code>  package IntIo is new TextIo.IntegerIo(int);
  package coerce is new UncheckedConversion(SomeTypeA, SomeTypeB);
</code>```

In C++, Stroustrup set it up so you write something like:

```<code>  TextIo.IntegerIo<int>.Put(x);
  ObjectOfTypeB := coerce<SomeTypeA,SomeTypeB>(ObjectOfTypeA);
</code>```

Stroustrup had to use SOMETHING to indicate the generic and its specialization.  He chose to overload angle brackets.  This initially created problems.  What if your template specialization required another template specialization, and you needed to close them both?  The lexer sees two closing >, or >>, and recognizes that as a shift operation.  A later language fix was required, to overload the shift operators << and >>.

Title: Why is this syntax convention?

Body:
It says in the book (APress Ganesh / Sharma) about Java 7:

You create a method named fill() in the Utilities class with this
  declaration:

```<code>public static <T> void fill(List<T> list, T val)
</code>```

You  declare the generic type parameter T in this method. After the
  qualifiers public and static, you put <T> and then followed it by
  return type, method name, and its parameters. This declaration is
  different from generic classes—you give the generic type parameters
  after the class name in generic classes.

But why <T> as in public static <T> ? The syntax looks odd and appears nowhere else in the Java language. What does the <T> mean in this case and why is it used?

Body:
From a 1995 interview with Alexander Stepanov in Dr Dobb's Journal: "I returned to generic library development in 1992 when Bill Worley, who was my lab director established an algorithms project with me being its manager. C++ had templates by then. I discovered that Bjarne had done a marvelous job at designing templates. I had participated in several discussions early on at Bell Labs about designing templates and argued rather violently with Bjarne that he should make C++ templates as close to Ada generics as possible. I think that I argued so violently that he decided against that. I realized the importance of having template functions in C++ and not just template classes, as some people believed. I thought, however, that template functions should work like Ada generics, that is, that they should be explicitly instantiated. Bjarne did not listen to me and he designed a template function mechanism where templates are instantiated implicitly using an overloading mechanism. This particular technique became crucial for my work because I discovered that it allowed me to do many things that were not possible in Ada. I view this particular design by Bjarne as a marvelous piece of work and I'm very happy that he didn't follow my advice."

In Ada, a generic must be instantiated, as for example:

  package IntIo is new TextIo.IntegerIo(int);
  package coerce is new UncheckedConversion(SomeTypeA, SomeTypeB);

In C++, Stroustrup set it up so you write something like:

  TextIo.IntegerIo<int>.Put(x);
  ObjectOfTypeB := coerce<SomeTypeA,SomeTypeB>(ObjectOfTypeA);

Stroustrup had to use SOMETHING to indicate the generic and its specialization.  He chose to overload angle brackets.  This initially created problems.  What if your template specialization required another template specialization, and you needed to close them both?  The lexer sees two closing >, or >>, and recognizes that as a shift operation.  A later language fix was required, to overload the shift operators << and >>.


答:
You need to know CSS. You should read about HTML and CSS, and how to make webpages.
Start with the absolute basics, it seems that you don't know them yet. </p>


问:
Why are different components of the "web platform" not modularized?
The web platform is hip these days.  But the web platform consists of many parts that are conceptually separable, developed at different times and paces, and (most important to me) could be useful on their own.  Basically the web platform is "a browser", but the browser lumps together several things:

HTML/CSS renderer

DOM

scripting on the renderer and DOM (JavaScript)

sandboxing (including cross-site scripting restrictions, limited access to local files, etc.)

the browser itself, which is a GUI app with its own look and feel

My question is, am I really the only one who thinks it would be useful to have each of these as separate components that are usable on their own, mixable and matchable with different versions of each other and with other programming tools?  The renderer/DOM are the ones I'd really like to see abstracted, because HTML/CSS is a very nice way to describe interfaces, but it's annoying that it can only be used to describe interfaces on a web page.

Most notably, the link between the rendering engine, JavaScript, and the browser GUI seems almost impenetrable.  This makes it really annoying to use HTML/CSS for interface design, because your interface is always going to be running inside a browser that you don't control, and you have to use JavaScript.  Compare that to other interface toolkits (like Tk, Qt, Wx), which often have bindings to multiple programming languages and can be leveraged in standalone apps that you have total control over.  (This means, for instance, that browser-wide user preferences for things like fonts can interfere with your presentation, and it means any menus, keyboard shortcuts, or other UI doodadssyou create have to compete with those of the enclosing browser.)

In similar fashion, it's very tough to write something that has an HTML/CSS interface, but stores data on your local computer, because browsers think it's an insecure web app, even if what you want it to be is just a "regular app".

I know there are historical reasons why people did all this together, but I find it baffling that at no point have people thought it would be worthwhile to make a separate, pluggable rendering engine that could be used with multiple programming languages, or a "browserapp maker" that would run a single web app in its own window, or anything like that.

Or, do such things already exist?  I'm aware of things like the web widgets in GUI toolkits, and XULRunner, but as far as I can see these still seem to be embedding a browser-like amalgam of several components.  (In particular, there does not appear to be a stable, mature rendering engine with DOM-access bindings for languages other than JavaScript.)  This makes them more heavyweight and less integrable into an application than it would be if you could just grab an HTML rendering library the same way you grab Qt or a PNG library or anything else.

答:
So, you know the historical reasons. And your text suggests that you have experience in matters of modularization and the technologies involved around the web subject. So I guess you probably know all or some of the following:

given the sad state of affairs, it is very hard to change in a way that doesn't break existing software.

Those things are so widely deployed and in such a "difficult to modularize" fashion that it seems (but is not necessarily known) that it is cheaper to build on top, than to adapt the platform.

Way too many people depending on too many idiosyncrasies to work as they are working right now and way too many people  required to agree before moving forward (hence, the existence of standard committees and so forth, involving people who may or may not have the qualifications for the task of defining high quality designs to solve yesterday's problems in specifications that will be half-baked implemented and used for decades to come).

Marketing and market competition can rule over technological merits.

I probably shouldn't put a question in an answer, but here is, in the name of thought provocation: have you tried what you propose? Of course, constraining the hypothetical solution to the obvious limitation that it should interop well with what already is there, keeping the existing portability properties while improving significantly the design.


问:
Avoiding boilerplate in PHP classes
I am working on a PHP code and as it grows getting more and more tired of repeating the same standard pattern again and again and again:

```<code>class BolerPlate
{
    protected $property1;
    protected $property2;
    ...

    public function __construct ($property1, $property2, ...)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
        ...
    }
}
</code>```

So I am re-typing here each property name 4 (!) times just to get the standard setup! In each class! It doesn't look elegant nor DRY to me. And re-typing the same names creates more bug opportunities.

I wonder if there is any more elegant way or best practices to get the same setup with a code easier on the eyes :)

EDIT. What I have in mind is some sort of factory method where I can supply the list of properties only once each. Or using variable variables and iterate over all properties?

答:
Here is some possible solution to my question inspired by this answer. In its laziest form it looks so:

```<code>public function __construct ($propertyArray) {
    foreach ($propertyArray as $property) {
        $this->$property = $property;
    }
}
</code>```

So you pass all arguments as array and then the code becomes uniform and can be inherited from. You still have to write the list of protected variables manually since the following (sadly) doesn't work:

```<code>    foreach ($propertyArray as $property) {
        protected $property; // or private $this->property
    }
</code>```

and there seem to be no easy way around :(.
The real problem here, far worse then just few extra lines to type, is the consequence of misprints, that can lead to creation of wrong private properties, whereas correct properties from the array become public against dev's intention.

The same problem actually affects the original traditional way just as much.

A partial solution is to use the trick inspired by the mentioned answer:

```<code>public function __construct ($propertyArray) {
    foreach ($propertyArray as $property) {
        $prefixedProperty = 'prefix' . ucfirst(strtolower($property));
        $this->$prefixedProperty = $property;
    }
}
</code>```

So you hide the property by adding 'prefix' to its name, so-called security by obscurity :). Now the property is still public in case of misprint but you hope not to hit it so easily. Still not 100% bullet-proof.

Now here is the best solution I came up with:

```<code>class BulletProof {
    protected $myProperty = '';

    public function __construct ($propertyArray) {
        foreach ($propertyArray as $property) {
            if (! isset($this->$property) ) {
               throw new exception("Careful, buddy! You either forgot or mistyped your declaration of $property!";
            }
            $this->$property = $property;
        }
    }
}
</code>```

So if you mistyped or forgot to declare the variable, compiler warns you with exception! To make it work, you have to initialize all your variables with something different from null, which is not too much of a burden, since they got overwritten by the constructor.

If anyone knows a more elegant way, I'd be happy to learn.

On another note I am grateful to Yannis Rizos for his suggestions in private chat, which involve using magic methods __set and __get, still with the consequence that properties become public.

Title: Avoiding boilerplate in PHP classes

Body:
Here is some possible solution to my question inspired by this answer. In its laziest form it looks so:

public function __construct ($propertyArray) {
    foreach ($propertyArray as $property) {
        $this->$property = $property;
    }
}

So you pass all arguments as array and then the code becomes uniform and can be inherited from. You still have to write the list of protected variables manually since the following (sadly) doesn't work:

    foreach ($propertyArray as $property) {
        protected $property; // or private $this->property
    }

and there seem to be no easy way around :(.
The real problem here, far worse then just few extra lines to type, is the consequence of misprints, that can lead to creation of wrong private properties, whereas correct properties from the array become public against dev's intention.

The same problem actually affects the original traditional way just as much.

A partial solution is to use the trick inspired by the mentioned answer:

public function __construct ($propertyArray) {
    foreach ($propertyArray as $property) {
        $prefixedProperty = 'prefix' . ucfirst(strtolower($property));
        $this->$prefixedProperty = $property;
    }
}

So you hide the property by adding 'prefix' to its name, so-called security by obscurity :). Now the property is still public in case of misprint but you hope not to hit it so easily. Still not 100% bullet-proof.

Now here is the best solution I came up with:

class BulletProof {
    protected $myProperty = '';

    public function __construct ($propertyArray) {
        foreach ($propertyArray as $property) {
            if (! isset($this->$property) ) {
               throw new exception("Careful, buddy! You either forgot or mistyped your declaration of $property!";
            }
            $this->$property = $property;
        }
    }
}

So if you mistyped or forgot to declare the variable, compiler warns you with exception! To make it work, you have to initialize all your variables with something different from null, which is not too much of a burden, since they got overwritten by the constructor.

If anyone knows a more elegant way, I'd be happy to learn.

On another note I am grateful to Yannis Rizos for his suggestions in private chat, which involve using magic methods __set and __get, still with the consequence that properties become public.


问:
What could be the advantages and disadvantages of decay of Nd arrays to N-level pointers?
I have been thinking of a couple of possible extensions to the C language which I'd like to know the opinion of others about.1 This one is about multi-dimensional arrays.

Imagine the following situation in C:

```<code>void matrix_mul(double **res, double **a, double **b, size_t n, size_t m, size_t r);
</code>```

You cannot pass a double mat[4][4] (for example) to this function. If you define the function as:

```<code>void matrix_mul_N_M_R(double res[N][R], double a[N][M], double b[M][R]);
</code>```

You'd just be wasting a perfectly written fine algorithm on a certain size of matrices.

What came to me (in shower obviously), was decay of multi-dimensional arrays to multi-level pointers. This is an extension to decay of 1d arrays to pointers.

Semantically, this would allow the first type of function to work on any two-dimensional array. Technically, this is how it would be implemented. The following code:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
matrix_mul(c, a, b, 3, 5, 4);
</code>```

would be equivalent to:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
double **__a_decay = {a[0], a[1], a[2]};               /* generated by compiler */
double **__b_decay = {b[0], b[1], b[2], b[3], b[4]};   /* generated by compiler */
double **__c_decay = {c[0], c[1], c[2]};               /* generated by compiler */
matrix_mul(__c_decay, __a_decay, __b_decay, 3, 5, 4);  /* first three arguments decayed */
</code>```

Is the application for such an extension very limited? Are there pitfalls? Could this possibly lead to insecure code where not using this feature wouldn't? Where else could such a feature come in handy?

1 Note that I'm not going to make another language myself, but would like to be sure of the feature's benefits and pitfalls before trying to suggest them to the C Standard Committee.

答:
The biggest problem with this seems to me to be that it's taking the C concept of arrays decaying to pointers and building on it.

Arrays decaying to pointers is already problematic in terms of clarity.  If you see a function that takes a parameter of type int*, does this mean it expects an array of integers, or a single integer as a "fake passed-by-reference" argument?  There's no way to know without examining the code of the function--or the documentation, assuming it exists and is up-to-date and accurate.

If you then expand on this to multiple levels of array-decay, the complexity and uncertainty grows exponentially with each dimension...


问:
Planning relational database - one or two tables?
I'm currently planning the database structure of a used car's advertisements site. Each advert contains information about a vehicle, and a vehicle can be advertised multiple times over its lifespan (granted, quite unlikely). I'm unsure which approach to take - a single table, or two separate relational tables, each has their pros and cons.

Schema 1

```<code>Adverts Table:
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int,
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
</code>```

Schema 2

```<code>Adverts Table
-------------------
id            int
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
vehicle_id    int

Vehicles Table
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int
</code>```

Personally, I'm thinking taking the second approach will benefit in the future, but it's proving tricky to work with. I'm using Laravel, a PHP framework. Because most of the "search" options are applied to the vehicle (parent), rather than the advert (child), a lot more code is required, which is starting to seem counter-intuitive. Schema 1 is far simpler to work.

Am I missing any extensive benefits of going with schema 2? In a nutshell, the first approach requires much less code, but isn't relational. The second approach is relational, but it's requiring far more code (and time), reducing the brevity of my adverts controller in particular, which is actually querying the vehicle's attributes more than the advert's. It's also making "sorting" quite tricky, as user's can sort by "make", "model", "location", "price", etc - attributes which jump between model.

答:
The decision between choosing a relational model over a de-normalized model is typically one of scale and the type of database operations that you anticipate most likely to occur.

A relational database is typically easier to query on and is more efficient for transactional heavy applications while a denormalized schema will be more appropriate if you plan on storing a large warehouse of data that you plan to run analytics or reports on.

If time is your bigger concern and you don't believe this site will have much traffic over the long term then by all means choose schema 1, but I recommend documenting the reasoning behind your eventual decision in the chance that someone else might be maintaining your work in the future and may be struggling with a feature that is at odds with your schema decision.

Myself, I would take the time to make it as relational as possible, but I am a perfectionist.

ProTip: Consider adding VIN number as a natural key to the vehicle table.  It will help you identify individual vehicles and it relates to a real easily identifiable attribute of a real vehicle.


答:
If these were the only two options, the first choice would be superior.  It's almost certain that each advertisement will map to one and only one vehicle; the only time the wouldn't is the edge case where someone sells a car without ever diving it.

Now, if practical, you could gain better utility by having a table for adverts and one for particular models of car: every 2008 Toyota carolla with the LX package has the same design features, for example.

the only times you'd want a one-to-one relationship between tables is if one table is shared with a different program, or if database optimization demands it fur performance reasons.  (and in the latter, the split should be hidden from the app if at all possible.)

Title: Planning relational database - one or two tables?

Body:
I'm currently planning the database structure of a used car's advertisements site. Each advert contains information about a vehicle, and a vehicle can be advertised multiple times over its lifespan (granted, quite unlikely). I'm unsure which approach to take - a single table, or two separate relational tables, each has their pros and cons.

Schema 1

```<code>Adverts Table:
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int,
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
</code>```

Schema 2

```<code>Adverts Table
-------------------
id            int
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
vehicle_id    int

Vehicles Table
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int
</code>```

Personally, I'm thinking taking the second approach will benefit in the future, but it's proving tricky to work with. I'm using Laravel, a PHP framework. Because most of the "search" options are applied to the vehicle (parent), rather than the advert (child), a lot more code is required, which is starting to seem counter-intuitive. Schema 1 is far simpler to work.

Am I missing any extensive benefits of going with schema 2? In a nutshell, the first approach requires much less code, but isn't relational. The second approach is relational, but it's requiring far more code (and time), reducing the brevity of my adverts controller in particular, which is actually querying the vehicle's attributes more than the advert's. It's also making "sorting" quite tricky, as user's can sort by "make", "model", "location", "price", etc - attributes which jump between model.


问:
Preparing to release code as open-source
I have developed a fully functional tool which I would like not only to share with anyone interested but also get support from the community. This tool is cross-platform, written in C++ with Qt, the code is well commented but I still lack any documentation. There are also some small issues and improvements to be made before I can call it a stable, final version.

What are the first steps that I have to take to release code as open-source and attracting people interested in contributing?

This is my first serious attempt to release open-source code and I really don't know where to start. Should I just push it to Github put together a small wiki and pray for the best?

答:
Before you look at the Other Advice consider:

Governance

How will your project be managed after you grant it to the community. The benevolent dictator model does work, but people will walk and fork if they dont get benefits from the code / project.

Code Ownership

Who owns the code is very important, as only the owners (in US Law) can take people to court to enforce copyright.

This is why the FSF tells contributors to grant ownership to them, and they in turn grant access to the code under the relevant licence (GPL, LGPL version 2.0 or 3.0).

Governance Organisations

I am not sure what is available in the PHP world, but there are a number of useful plaforms and ecosystems for code governance. Each with their own licence and governance structure.

Free Software Foundation GNU Licences

Eclipse.org Eclipse Public Licence

Apache.org Apache Licence

Other Licence Considerations

Where will the code be used, who will re-deploy it, what are the current licences that similar and platform code are deployed under. All these issues provide guidance as to what licence should be used.

If there isnt already a community of interest that you can leverage it is very hard to have a successful project just by yourself.


问:
How to insert a database layer in PHP
I maintain and add features on a freelance basis to a website written in PHP. The application was started in PHP4 by a junior programmer back in 2006, and features some very insecure and unmaintainable ways of doing things, which I am trying to correct as time goes on. If the client agrees, one of the first things I would like to do is add in a proper database layer of some sort.

The current database access looks like this:

```<code>if (!function_exists('my_query')) {
function my_query($query) {

    if ($query=='disabled') return false;

    global $last_insert_id,$dbconn,$dbase;

    $result=mysql_query($query,$dbconn) or die('ERROR: '.mysql_error($dbconn).'<br />'.$query);
    $last_insert_id=mysql_insert_id($dbconn);
    return $result;
}
}
</code>```

There is also a function to make arrays from the data returned.

```<code>if (!function_exists('spawnarray')) {
function spawnarray($result)
{
    $i = 0;
    if ($result != "") {
        if (mysql_num_rows($result) > 0) {
            while($result_obj[$i] = mysql_fetch_object($result)) {
                $sp_result[$i]=$result_obj[$i];
                $i++;
            }
            return $sp_result;
        }
    }
}
}
</code>```

These two functions are basically the database layer, and SQL queries are constructed on the fly for them all over the place.

So my question is, how can I start to introduce database abstraction in to the mix? I would like to move to PDO for security and ease of use reasons, but maybe there is a better way to go?

I have already moved the project to Composer for some of its dependencies (Some are dead projects, which is a different issue) so maybe an ORM like Doctrine would be the way to go? That might mean moving the website to OOP in one go though: a daunting prospect, and a sure no-go from the client.

答:
You can also use Zend Framework's Zend\Db, as you go. You don't need to have a major overhaul to implement it, you can start using it for new code only. When the client approves, you can start converting old code to use Zend\Db too. This way you're not adding some more piece of code to maintain, just use off the shelf component.

The advantage is not only you will replace the old database layer, you will also be able to 'lift' the implementation to use higher level concept such as the Table Gateway and Row Gateway, both are supplied in Zend\Db.

Same reason can be said about Doctrine too, you can use it where you want it, although it is heavier than Zend\Db. It depends on the problems you want to solve too, e.g. do you need Domain Model.

Title: How to insert a database layer in PHP


问:
How can web development bootcamps deliver on their promise?
I came across the concept of web development bootcamps, these 9-10 week intensive crash courses claim to teach beginners web development and help them get 80k starting salary jobs. Many of you might have heard of these.

Is what the bootcamps promise feasible? Is it possible for web technologies like Ruby on Rails, HTML5, CSS, and Javascript to be taught from scratch in such a short period? And to people without a technical background?

答:
Short version: Its possible to teach a person to write a simple ruby crud app in 9 weeks.  This roughly mirrors the first semester college class. Many companies need that.  The trick to getting them hired is to get lots of people with entry level skills in a room with lots of companies that want entry level people.

As mentioned in the wikipedia article for dev bootcamp (emphasis mine)

The program is 9 weeks of intensive training in professional web development, including Ruby on Rails, HTML5, CSS, and Javascript. The program takes students with little or no prior programming experience and teaches them the fundamentals of computer programming. The program's goal is to develop the necessary skills within the students to make them job-ready for an entry-level developer position

They're working on Rails (which is reasonable for CRUD apps), and a few basic bits of markup.  Its designed for someone who has no experience in programing or familiarity with learning how to learn a programming language.

To this extent, yes, one could take someone who has no experience and make them an entry level CRUD web programmer.  They can toss together a form with ActiveRecord and erb in Ruby, add some formatting in CSS and a little bit of validation in javascript.  And do this in 9 weeks.  Given the phrasing of "9 weeks" and "intensive training" this about matches a semester of college (with the 'intensive' part to get people to understand how to program).

tuition costs are $12,200 for the 9 week, 40 hour per week program. Although traditional class hours are 9am-6pm on weekdays, most students stay nights and weekends, which amounts to an approximate 70-80 hours per week

... well  I know what my next job will be.

The key to the results is not the training. And quite frankly, if the person doesn't have the right mindset to learn how to program or the curiosity to do more and better - they'll remain forever at entry level.  There is a call for that (in some markets there is a lot more openings than people filling them - which brings us to...)

Another point to consider when they advertise the average starting salary, one needs to look at salaries.  For example in San Francisco the median pay for a person who sits at the front desk and organizes mail is $52k, and the person who sits in front of a director or C?O and does the same is $62k.  A software engineer has a median salary of $93.  $85k is not a lot in San Francisco. (see also cost of living in San Francisco - seriously, the rent in SF for a year is more than many people make elsewhere in a year)  Similar things can be said of Chicago.

Dev Bootcamp organizes hiring days for technology companies to interview students. They then collect a referral fee from employers that hire their graduates, and they pass along part of that fee to the graduate in the form of a hiring bonus.

The key to getting people hired is getting them face time with the various companies.  Its the connections in this case - of the recruiters who want the front line of coders and the dev bootcamp organizers.  This can also be done outside of a boot camp (give your information to a head hunter - they have similar access).

The dev bootcamp is unlikely to get into data structures (its fortunate that Ruby has so few), nor various parts of theory that helps one write better code.  They are teaching people to write simple applications.  There are many times when companies are just after simple applications.

How well these applicants do long term is yet to be seen - dev boot camp was founded in 2012.  Many of these students and new hires haven't even had their first year's performance reviews yet.

I will point out that this is based on dev bootcamp itself which is in SF and Chicago, and information relating to the skilled programer job market in those two cities.  The job markets in other regions of the United States or other nations is beyond my familiarity.

It is important to engage existing career finding resources (like headhunters and friends who can get a referral bonus for giving a resume to HR).  All of this is for naught if the market is over saturated with people looking for jobs (it is in some areas).

Going to such a class and expecting to find an $85k job afterwards in rural Montana won't happen.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答: My favorite is to start with asking the prototype of printf. Then given a low level API printc(char c), which will print one character, implement printf. Gives all sorts of interesting responses like the stack is part of the CPU. As you might have guessed I am from a C and embedded background.</p>


答:
My rule of thumb for such decisions is: if the database is used as the source of that data, and the data is maintained manually in that database (OLTP), keep it as normalized as possible, that will prevent you from horrify headache later on. You should consider to split it into more than 2 tables then.

If, however, the data is not maintained in that db, but only loaded there automatically from a different source and then never changed until the db gets cleared (for example, for reporting purposes, or for an OLAP database), you should use the structure which supports your reporting best, which may be the one-table solution.

Did you consider to use the 2 tables approach together with a joined view? The view could deliver you the data just like schema 1, making your concerns about "far more code" and "tricky sorting" most probably pointless.


答:
Perhaps you have heard the famous quote of Antoine de Saint-Exupery before:

A designer knows he has achieved perfection not when there is nothing
  left to add, but when there is nothing left to take away.

So before thinking about language extensions one should think about solving a problem with the existing language features in a convenient way (and I guess that's what the C standard commitee will answer you if you really make such a proposal).

In C, the natural solution to this kind of problem is to define a

```<code>struct Matrix
{
    int sizeX;
    int sizeY;
    double *values; /* vector with sizeX * sizeY elements */
};
</code>```

(or something similar), and create operations working on that kind of data type, including operations for memory allocation and freeing, operations to fill that kind of structure with values from a 2D-array etc.

Title: What could be the advantages and disadvantages of decay of Nd arrays to N-level pointers?

Body:
I have been thinking of a couple of possible extensions to the C language which I'd like to know the opinion of others about.1 This one is about multi-dimensional arrays.

Imagine the following situation in C:

```<code>void matrix_mul(double **res, double **a, double **b, size_t n, size_t m, size_t r);
</code>```

You cannot pass a double mat[4][4] (for example) to this function. If you define the function as:

```<code>void matrix_mul_N_M_R(double res[N][R], double a[N][M], double b[M][R]);
</code>```

You'd just be wasting a perfectly written fine algorithm on a certain size of matrices.

What came to me (in shower obviously), was decay of multi-dimensional arrays to multi-level pointers. This is an extension to decay of 1d arrays to pointers.

Semantically, this would allow the first type of function to work on any two-dimensional array. Technically, this is how it would be implemented. The following code:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
matrix_mul(c, a, b, 3, 5, 4);
</code>```

would be equivalent to:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
double **__a_decay = {a[0], a[1], a[2]};               /* generated by compiler */
double **__b_decay = {b[0], b[1], b[2], b[3], b[4]};   /* generated by compiler */
double **__c_decay = {c[0], c[1], c[2]};               /* generated by compiler */
matrix_mul(__c_decay, __a_decay, __b_decay, 3, 5, 4);  /* first three arguments decayed */
</code>```

Is the application for such an extension very limited? Are there pitfalls? Could this possibly lead to insecure code where not using this feature wouldn't? Where else could such a feature come in handy?

1 Note that I'm not going to make another language myself, but would like to be sure of the feature's benefits and pitfalls before trying to suggest them to the C Standard Committee.

Body:
Perhaps you have heard the famous quote of Antoine de Saint-Exupery before:

A designer knows he has achieved perfection not when there is nothing
  left to add, but when there is nothing left to take away.

So before thinking about language extensions one should think about solving a problem with the existing language features in a convenient way (and I guess that's what the C standard commitee will answer you if you really make such a proposal).

In C, the natural solution to this kind of problem is to define a

struct Matrix
{
    int sizeX;
    int sizeY;
    double *values; /* vector with sizeX * sizeY elements */
};

(or something similar), and create operations working on that kind of data type, including operations for memory allocation and freeing, operations to fill that kind of structure with values from a 2D-array etc.


答:
It's not a question about 1 or 2 tables. Consider:

```<code>Vehicles Table
-------------------
id            int
make          varchar(255),
model         varchar(255),
..
..
</code>```

or:

```<code>Vehicles Table
-------------------
id            int
make          varchar(255),
modelid       int
..
..

VehicleModel Table
-------------------
modelid       int
modelname     varchar(255),
..
</code>```

A good thought out design will make your database that much easier to extend.

Body:
It's not a question about 1 or 2 tables. Consider:

Vehicles Table
-------------------
id            int
make          varchar(255),
model         varchar(255),
..
..

or:

Vehicles Table
-------------------
id            int
make          varchar(255),
modelid       int
..
..

VehicleModel Table
-------------------
modelid       int
modelname     varchar(255),
..

A good thought out design will make your database that much easier to extend.