问:
How effective are "game programs" in interviews?
I write business applications for a living.  Often, for whatever reason, an interviewer asks me to write up a program to solve some kind of game like problem.  I find this to be an inappropriate question for two main reasons:

Games often deal with constructs that are rarely used in business dev.  E.G. Multi-dimensional arrays. Store player locations on a checkerboard for instance. (Maybe it's just me, but I never use these things in biz)

My usual tools like BL/DL, ORMs and even designing the entities themselves don't translate well.  So I often end up with some goofy lookin code to start.  This is especially awkward if the interviewer is looking over your should to determine how "well you code".  Horribly uncomfortable, because...well I don't code like that...I don't write games for a living either.

Do you folks use them in your interviews and have they been effective for learning about a business apps dev?

答:
Thats odd, I have never had that experience.  I get the exact opposite end of that spectrum. I usually get something like this "..we are experiencing this particular business/tech problem for these reasons, how would you go about solving it".  My interviews have always had much more practical questions.

When I interview people I tend to to go with asking about current work they are doing and then digging in deeper on areas that are relevant.  I usually get a very good sense of the persons ability and passion about what they do by digging in.  Are they getting excited about the problems they solved, are they offering up details about the challenges or am I having to dig them out etc.


答:
I have used them in my interviews and I have been asked similar question in interviews.  Most of these questions are designed to gauge how well can you break a task into smaller components and how "neatly" for the lack of the better word can you make interactions between the components.

Normally I don't hover over the interviewee while he or she is doing the task but periodically I'd like to look at their work to gauge their train of thought.  This type of technique is also used to gauge how well a person can tune out the yell for "Get it done! Get it done! Get it done!" and actually focus to do the right thing.

Typical questions I saw was to design objects for the game of chess, checkers, tic-tac-toe or something similarly simple.  Writing implementation of methods is usually not required for things like this.

ContentLicense: CC BY-SA 3.0

Title: How effective are "game programs" in interviews?

Body:
I write business applications for a living.  Often, for whatever reason, an interviewer asks me to write up a program to solve some kind of game like problem.  I find this to be an inappropriate question for two main reasons:

Games often deal with constructs that are rarely used in business dev.  E.G. Multi-dimensional arrays. Store player locations on a checkerboard for instance. (Maybe it's just me, but I never use these things in biz)

My usual tools like BL/DL, ORMs and even designing the entities themselves don't translate well.  So I often end up with some goofy lookin code to start.  This is especially awkward if the interviewer is looking over your should to determine how "well you code".  Horribly uncomfortable, because...well I don't code like that...I don't write games for a living either.

Do you folks use them in your interviews and have they been effective for learning about a business apps dev?


答:
It's one of those "We want to inteview like Google/Facebook/Amazon/etc" questions. Unless you're actually interviewing for a position at a game company, it wouldn't be useful to ask such questions. It would be more valuable to discuss/test something related to the problem domain of the company. For example, if I wanted you to write a web service to handle different formats of daily pricing feeds from 50+ different vendors I'd ask how you would approach it and have you sketch out, with some pseudo-code, how you would do it.

I did get asked gaming questions like this in an interview once, at a company developing a MMORPG. Sadly, I didn't get that job.


答:
I agree that trying to code while someone is staring over your shoulder is distracting.

My take on the game idea is that it allows you to get a feel for if the candidate can take a bizarre, off-the-cuff problem and come up with a workable solution to it.  It is not like they are asking you to have multiple moving sprites and arc vectors or anything that requires memorization of trigonometry.

They are asking you to do Checkers, because it is a simple game, simple set of rules, clear outcomes, and requires the use of a data structure more complicated than just an array.  The question is legitimate.


问:
Code Correctness (?) Annotations for Java (and other languages)?
After writing my billionth null check in Java code, I started wondering why the ability to null check method arguments wasn't already built in to Java.  For example, for some methods, I want to throw an IllegalArgumentException if some (or all) of the arguments are null. It would be great if I could mark up the code, and have the compiler generate the validation which throws an informative Exception if the validation fails.

Is there anything already in Java where you can specify some correctness parameters for method arguments (e.g. int has to be within certain range, or Object has to be not null), and have the Compiler auto-generate the code?

In Java it seems like this should be handled with annotations. (I guess in C/C++ you could define some nice macros to do this for you.)  In searching the web on this issue, I saw reference to JSR 305, but this seems targeted toward use with IDE tools, and not with the Java compiler.

I'm guessing this already exists in other programming languages.  So I would be interested to hear about how this may work in these languages, as well as what might exist (or be coming up) in Java.

答:
Not in standard Java.

The cleanest syntax in a widely used library is perhaps the one in Google Guava.

```<code>public void fullyImplementedGuavaConstructorWouldBe(Long id, String firstName, String lastName, String login) {
        this.id = checkNotNull(id);
        this.firstName = checkNotNull(firstName);
        this.lastName = checkNotNull(lastName);
        this.login = checkNotNull(login);

        checkArgument(firstName.length() > 0);
        checkArgument(lastName.length() > 0);
        checkArgument(login.length() > 0);
    }
</code>```

(from http://blog.solidcraft.eu/2010/10/googole-guava-v07-examples.html)

Javadoc: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html#checkNotNull(T, java.lang.Object)

Body:
Not in standard Java.

The cleanest syntax in a widely used library is perhaps the one in Google Guava.

public void fullyImplementedGuavaConstructorWouldBe(Long id, String firstName, String lastName, String login) {
        this.id = checkNotNull(id);
        this.firstName = checkNotNull(firstName);
        this.lastName = checkNotNull(lastName);
        this.login = checkNotNull(login);

        checkArgument(firstName.length() > 0);
        checkArgument(lastName.length() > 0);
        checkArgument(login.length() > 0);
    }

(from http://blog.solidcraft.eu/2010/10/googole-guava-v07-examples.html)

Javadoc: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Preconditions.html#checkNotNull(T, java.lang.Object)


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

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

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

答:
Setting up for all tests can be a good idea, particularly if you do a deploy. Instead of using mocks we create, deploy and populate a test database and then point the test at the instance.
Not exactly the way you should do it as per the manual, but it works, even more so for us because we use our deployment code to do it.</p>

OwnerDisplayName: JDT

OwnerDisplayName: Tony Hopkinson


答:
I would warn for having too much code that does too much 'black magic' without developers knowing what exactly is being set up. Also, in time, you'll become very dependent on this code/data. That's why I'm no fan of basing your tests on test databases. I believe test databases are for testing as a user, not for automated tests.

That said, your problem is real. I'd make some common methods to set up data you need regularly. Ideally, try to parameterize the methods, because certain tests need different data.

But I'd avoid creating big object graphs. It's best to have tests run with the minimum of data they need. If there's a lot of other data, you could unexpectedly influence your test results (worst case scenario).

I like to keep my tests as "silo'ed" as possible. It is a subjective question though. But I'd go for common methods with parameters so that you can set up your test data in only a few lines of code.

Title: Advantages and disadvantages to making common unit test scaffolding code

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

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

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

OwnerDisplayName: Peter


答: You might want to reconsider the design of the code you are testing. Perhaps it needs some instances of the Facade design pattern? Your test code could use the Facades, and would be simpler.</p>

OwnerDisplayName: Raedwald


答:
```<code>Creating domain objects with correct values
</code>```

I use the builder pattern to create domain objects for tests as detailed in the "Growing Object-Oriented Software" book. The builders have static methods that generate default values for common objects with methods for overriding the default values.

```<code>User user = UserBuilder.anAdminUser().withEmail("test@example.com").build();
</code>```

You can combine these to generate more complex objects.

We also use test case class inheritance with commonly used mocks for specific types of unit tests - e.g. mvc controller tests frequently require the same mocks/stubs for request & response objects.

Body:
Creating domain objects with correct values

I use the builder pattern to create domain objects for tests as detailed in the "Growing Object-Oriented Software" book. The builders have static methods that generate default values for common objects with methods for overriding the default values.

User user = UserBuilder.anAdminUser().withEmail("test@example.com").build();

You can combine these to generate more complex objects.

We also use test case class inheritance with commonly used mocks for specific types of unit tests - e.g. mvc controller tests frequently require the same mocks/stubs for request & response objects.

OwnerDisplayName: Bedwyr Humphreys


答:
If you're using the Spring framework, it's possible to use Assert to handle input checks:

```<code>public String modifyString123(String myString) {
    Assert.hasText(myString, "myString can not be null or empty");
    return myString + "123";
}
</code>```

An IllegalArgumentException will be thrown if the input is null or empty.

Title: Code Correctness (?) Annotations for Java (and other languages)?

Body:
After writing my billionth null check in Java code, I started wondering why the ability to null check method arguments wasn't already built in to Java.  For example, for some methods, I want to throw an IllegalArgumentException if some (or all) of the arguments are null. It would be great if I could mark up the code, and have the compiler generate the validation which throws an informative Exception if the validation fails.

Is there anything already in Java where you can specify some correctness parameters for method arguments (e.g. int has to be within certain range, or Object has to be not null), and have the Compiler auto-generate the code?

In Java it seems like this should be handled with annotations. (I guess in C/C++ you could define some nice macros to do this for you.)  In searching the web on this issue, I saw reference to JSR 305, but this seems targeted toward use with IDE tools, and not with the Java compiler.

I'm guessing this already exists in other programming languages.  So I would be interested to hear about how this may work in these languages, as well as what might exist (or be coming up) in Java.

Body:
If you're using the Spring framework, it's possible to use Assert to handle input checks:

public String modifyString123(String myString) {
    Assert.hasText(myString, "myString can not be null or empty");
    return myString + "123";
}

An IllegalArgumentException will be thrown if the input is null or empty.


问:
Beginners guide to developing optimization software
I am novice in "serious" programming i.e. applications that deal with real-life applications and software projects that go beyond school assignments.

My interests include optimization, operations research, algorithms and lately i discovered how much I do like software design/development/engineering.

I have already developed some simple desktop applications for some "famous" problems like TSP using heuristc approaches, a VRP solver (in progress) and so on.

While developing this kind of software I actually used basic concepts taught at school such as object-orientation analysis and design. But, I found these courses rather elementary and quite boring (for my expectations).

So I decided to go a little further and start developing "real" software (and this is where I realized how important and interesting software engineering/design is.)

Now, here's my issue: I can not find a "study guide" for developing software of this kind.

Currently, there are numerous resources out there (books, websites, tutorials) in designing and developing complex IS, web applications, smartphone apps but I can't find a book for example entitled "optimization software development". Definetly, someone could claim that "design patterns apply to software in general" but that's not my point.

My point is that I could simply use my imagination for "simple" implementations, but what happens, when my imagination can not go further?

In other words I'm looking for a guide/path to bridge the gap between:
Mathematics-Algorithm Design-Software Engineering-Optimization-Software development

答:
I believe part of the problem you are experiencing is that such software developed for businesses, rather than software developed for mass market (aka "shrink-wrapped" or consumer) are developed and sold as solutions rather than as applications, for the most part.

Some of these businesses have a base product, and sell the package with customization consulting, which is essentially developing an formal encoding of the "business rules" or "business logic" for that client's business. This is necessary as the client actually wants a solution to their problem, not a complex system that can manipulate symbols and numbers. The companies train and foster their own in-house (e.g. IBM) and external consultants (SAIC) who specialize in supporting their product and its customization for clients.

I suspect the majority of this knowledge falls into either the academic side of fence (SIAM may be your best source of journals and books) or in-house corporate knowledge that is not widely shared, as the particular markets may be perceived as small (few competitors).

One place where you may find a community of people willing to share their knowledge is academic supercomputer centres, which may even provide a workplace to transition from your seemingly academic background to a more development oriented experience and role.

I don't know for sure, it is totally outside my sphere of knowledge/ experience, but one potential area to consider might be the field of data mining, where the data sets are so large that more advanced approaches to extracting useful information may tap Optimization and OR approach.

Military and domestic intelligence organizations (e.g. NSA, CGHQ, CSE) may be places of application and/or employment if you are interested.

I don't know if a department like U Waterloo's C&O department may have additional suggestions. Otherwise what is generally called as "scientific computing" may be the closest to what you are looking for.

Such focus is outside my own background, but I hope that helps give you some places to consider or look into.


答:
Most programming quizzes should focus on whether the applicant can program AND test logic/problem solving.  Programming and logic/problem solving are both very important.  It's not that easy to come up with a generic and challenging quiz, to get good programmers/problem solvers to work for you.

I think the game aspect of the interview is trying to test the logic/problem solving ability of the programmer, and in that regard, as long as the question is not too clever or obtuse, I think it is a reasonable method to test a programmer's problem solving ability.

That being said, quizzes are a rabbit hole few companies get right.

In general, a reasonable programmming quiz should be three parts:

Fizz buzz type of question to weed out applicants who can't program

A general question to test coding and logic/problem solving skills (this can be difficult to craft)

A speciic question to test industry skill and experience (for example, if database, then maybe some SQL type of questions, join tables, etc.)


问:
How do you do to create the ViewModel part of your MVVM designs?
Sometimes, when I plan to create a program using this architectural pattern, I've got a lot of difficulties when I'm in the View Model phase.

I'm using WAF Framework to develop this architectural pattern. I'm a still a newbie.

Before you start, do you create all the UML design or do you use another tool to help you? How do you handle the design of your ViewModels ?

答:
The ViewModel is an abstraction of the View.

That means you need to know first what you want to diplay to the user. At least you should have a detailled sketch of what the UI will look like (There are many tools intended to do this: MS Expression Blend, Balsamiq, etc.). Or even a dummy UI without logic plugged behind, created with your development tool.

Once you have your view, the ViewModel will be the place to hold every binded value, and what could be called display logic, mainly formatting. A View Model can be a representation of one Model, a group of Models of the same type, or an aggregation of different models.

A simple exemple of View Model is the editing screen with a drop down list. Let's have a concrete example with a User that can be linked to a division :

```<code>public class UserModel
{
   public string Username { get; set; }
   public string EmailAddress { get; set; }
   public int DivisionId { get; set; }
}

public class DivisionModel
{
   public int DivisionId { get; set; }
   public string DivisionName { get; set; }
}
</code>```

It wouldn't make sense to plug an IEnumerable of divisions in UserModel, so we create a View Model to represent a displayable User, with all the data needed to have a working screen where I can select a Division for that User :

```<code>public class UserViewModel
{
   public UserModel User { get; set; }
   public IEnumerable<DivisionModel> Divisions {get; set;}
}
</code>```

And that's it. Depending on the language I'll be using, I'll just have to feed a drop down list with the IEnumerable of DivisionModels and make it show the Name member.

Body:
The ViewModel is an abstraction of the View.

That means you need to know first what you want to diplay to the user. At least you should have a detailled sketch of what the UI will look like (There are many tools intended to do this: MS Expression Blend, Balsamiq, etc.). Or even a dummy UI without logic plugged behind, created with your development tool.

Once you have your view, the ViewModel will be the place to hold every binded value, and what could be called display logic, mainly formatting. A View Model can be a representation of one Model, a group of Models of the same type, or an aggregation of different models.

A simple exemple of View Model is the editing screen with a drop down list. Let's have a concrete example with a User that can be linked to a division :

public class UserModel
{
   public string Username { get; set; }
   public string EmailAddress { get; set; }
   public int DivisionId { get; set; }
}

public class DivisionModel
{
   public int DivisionId { get; set; }
   public string DivisionName { get; set; }
}

It wouldn't make sense to plug an IEnumerable of divisions in UserModel, so we create a View Model to represent a displayable User, with all the data needed to have a working screen where I can select a Division for that User :

public class UserViewModel
{
   public UserModel User { get; set; }
   public IEnumerable<DivisionModel> Divisions {get; set;}
}

And that's it. Depending on the language I'll be using, I'll just have to feed a drop down list with the IEnumerable of DivisionModels and make it show the Name member.


问:
What are some examples of "wartiness" making a programming language more useful?
From the accepted answer to "Why is Lisp useful?":

 5. Wartiness. The real world is messy. Pragmatic coding winds up having to either use or invent messy constructs. Common Lisp has
  sufficient wartiness that it can get stuff done.

This thought has occurred to me, too.  I'm currently developing an application whose backend I chose to write in Haskell, and whose frontend is in PHP.  My experience has been that dealing with messy code in PHP is much easier than dealing with messy code in Haskell.  However, it's my own code, and my PHP code probably isn't all that bad.

A simple example of "wartiness" is PHP's == (equality) operator.  You know, the type of equality where '' == 0 is true.  Since I'm wary of ==, I often choose to use PHP's === (strict equality) operator instead:

```<code>$is_admin = ($gid === 24 || $gid === 25);
</code>```

However, the above usage turned out to be wrong.  The $gid value came from the database, and is still a string.  This time, the strict equality operator bit me, and I would have saved myself a few minutes by simply saying:

```<code>$is_admin = ($gid == 24 || $gid == 25);
</code>```

Consider another interesting identity:

```<code>php> var_dump('0012345' == '12345');
bool(true)
</code>```

What the heck?!  == on two strings isn't even string comparison!  However, consider if the user is given an ID card that says 0012345, but the database ID is simply 12345.  Users may have trouble logging in to your application if you chose to use ===.  Sure, you'll get a bug report, and you'll be able to make your application correct rather than relying on this obscure feature.  But it'll take more time.  I'd rather spend that time outside.  It's a really nice day.

By contrast, here's an example of wartiness that is not helpful in most cases:

```<code>js> parseInt(031);
25
</code>```

What are some more concrete examples where "wartiness" helps you Get Things Done?  Please explain why; don't just list features Haskell doesn't have.

Another way of putting it: what are some warty language features to be aware of, and how can we use them to save time?

答:
Quick example, not the best.

In CL, Truth is anything not nil.   That is kind of sketchy, right? Typically, you want to see if something is True, not determine if it's not-nil.  True is a subset of non-nil.

But if you squint a bit, you realize it doesn't actually matter most of time, and also it reduces the size of code, instead of asking (if (eq foo #t) this that), you can do (if foo this that).  Scheme takes the first approach.

I'm reasonably sure a PL designer can give some great discussions here, but unfortunately, that's not me today.

To quote a quote of vague provenance...

Schemer: "Buddha is small, clean, and serious."

Lispnik: "Buddha is big, has hairy armpits, and laughs."

Also, I'm quoted. Woot!


答:
JSR-303 - Is the standard for Bean Validation and is supported by Hibernate Validator and several other frameworks. It supports the sort of annotation based range checking and not null checking that I think you're after.

The Bean Validation specification is actually going through an update at the moment, so expect more possibilities in the near future.


问:
Pair Programming with Scrum
I'm on a team that is currently using Scrum, and we're considering adding pair programming to help improve the cross-functional skills of the team, as well as help reduce defects with a "two heads are better than one" philosophy.

On our team, each team member typically signs up for a full workload during sprint planning (with "full" being a number that is less than 40 hours a week, allowing for meetings, collaboration, etc.), with a single dedicated owner for each task.  I believe this is fairly common on Scrum teams but may not necessarily be by the book.

In particular, I'm looking to avoid a situation where team members are hesitant to pair because they have their own tasks to work on, which I'm afraid is likely to happen if the team simply self-organizes without time set aside for pairing.

Given this, what is the best way to account for effort/hours/story points in a pairing scenario, to make sure we have appropriately allotted time for pairing?

Some options considered are:

Allow two people to sign up for each task and (roughly) double the number of estimated hours

Only the "hands on keyboard" team member signs up for each task, which is estimated based on that person's estimated hours.  Anyone on the team who will be supporting pairing will sign up for fewer tasks in the sprint to allow time to support pairing.

答:
Scrum does not mandate that tasks be assigned to individuals--far from it.  The responsibility for tasks to be completed fall on the Team as a whole.  If the team wants to do pair programming, where each pair picks up a task, they most certainly should do so.

From the Scrum Guide:

The Development Team usually starts by designing the system and the work needed to convert the Product Backlog into a working product increment. Work may be of varying size, or estimated effort. However, enough work is planned during the Sprint Planning meeting for the Development Team to forecast what it believes it can do in the upcoming Sprint. Work planned for the first days of the Sprint by the Development Team is decomposed to units of one day or less by the end of this meeting. The Development Team self-organizes to undertake the work in the Sprint Backlog, both during the Sprint Planning Meeting and as needed throughout the Sprint.

Title: Pair Programming with Scrum


答:
What you're trying to do is sometimes called Designing By Contract.  There are a number of frameworks that achieve this goal, and you can define more than just null checks, but most any kind of pre or post condition, too.

A quick Google search shows a few good solutions for Java:

Contracts for Java Uses annotations (as you have suggested):

```<code>interface Time {
 ...

 @Ensures({
   "result >= 0",
   "result <= 23"
 })
 int getHour();

 @Requires({
   "h >= 0",
   "h <= 23"
 })
 @Ensures("getHour() == h")
 void setHour(int h);

 ...
}
</code>```

jContractor Uses separate classes

```<code>protected boolean Stack_Precondition (Object [] initialContents) {
    return (initialContents != null) && (initialContents.length > 0);
}
</code>```

This should get you started.

Body:
What you're trying to do is sometimes called Designing By Contract.  There are a number of frameworks that achieve this goal, and you can define more than just null checks, but most any kind of pre or post condition, too.

A quick Google search shows a few good solutions for Java:

Contracts for Java Uses annotations (as you have suggested):

interface Time {
 ...

 @Ensures({
   "result >= 0",
   "result <= 23"
 })
 int getHour();

 @Requires({
   "h >= 0",
   "h <= 23"
 })
 @Ensures("getHour() == h")
 void setHour(int h);

 ...
}

jContractor Uses separate classes

protected boolean Stack_Precondition (Object [] initialContents) {
    return (initialContents != null) && (initialContents.length > 0);
}

This should get you started.


问:
Comment before or after the relevant code
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.

答: Having the comment appear before the code helps the reader have a context for the code they're about to encounter. Much more humane than throwing the code at them and explaining after they're already confused.</p>


问:
How do I report software vulnerabilities found in an open source library that are widely used but have a dilapidated team structure?
For most open source project, there is a well-founded project team and corporate sponsorship, and a lot of active contributors. The procedure for filing bug reports are clearly documented.

However, there are also some open source project(s) that have been in existence for more than 10 years (maybe 15), and were included in all sorts of free and commercial products (OSes and linux distros, etc), and everyone just assumes it is correct, despite some parts of it in a state of despair and full of bugs.

It appears to me that the real users (programmers in-the-know) simply choose to use the library in a certain way as not to trigger the bug. Few choose to speak up.

There are also big-name companies that fix the bugs quietly (in their own products) without giving out any patches. And use that to their business advantage.

There is no leading developer. There is no information as to who are the active developers, except that you can browse the mailing list and see who has recently submitted patches, and assume that they might know someone who is helpful.

How should I handle a vulnerability case, without leaking information in a way that gives ammunition to the bad guys?

This question is a spin-off from: https://softwareengineering.stackexchange.com/questions/5168/whats-the-biggest-software-security-vulnerabilty-youve-personally-discovered

答:
Talk to Secunia (or any of the other bug databases), and let them handle it.

They do this on a daily basis, and probably already have a procedure for if they can't identify an appropriate contributor for a project.

(I would guess, if there's no contacts for the library itself, they'd contact major projects currently using the library, allowing any widespread software to fix/workaround any security issues, before releasing details to the public.)

ContentLicense: CC BY-SA 2.5


问:
When should I invalidate a cache of a user's credentials?
We develop a Windows client application that locally caches a user's credentials for connecting to our server application using the Windows Credential Management API.

Our caching logic works in the following way:

The user opens the application and selects a server in the UI.  It then queries the server for authentication requirements.  (If no credentials are needed, then we just connect without authentication.)

The application reads the cache to see if there are cached credentials.

If there are existing cached credentials, they are used.  Otherwise, the Windows API is used to bring up a dialog box.

The application attempts to authenticate with the server using the credentials.

If the connection is a success, then the credentials used are cached for the lifetime of the Windows session (this is a feature of the Windows API).  Otherwise, we clear the cache and return to step 3.

The question is: are there other valid situations where the credential cache should be cleared?  In other words, what would you consider to be best practices on how to manage the lifetime and invalidation logic for this potentially sensitive information?

(Since I will probably be asked, the information we store using this API is encrypted using our own encryption logic, and stored in memory via SecureString.  No doubt there are potential holes in this approach, but that is for another discussion.)

答:
It depends on the security sensitivity of the application, and the environment in which it is used.

If this application is used by a business whose employees log off their machines at the end of their shifts, it is probably ok to keep the credentials cached for the Windows session. If they leave their computers logged in and unattended, then someone else with physical access could hijack their session.

An alternative is to cache the credentials (or a session token) for the session of the client application (or until the user tells it to log off). This allows the user to end just that session when they are done, which would be good for a more sensitive application. An inactivity timeout could also trigger a log off.

In evaluating what approach is appropiate for a givin situation, I would use a strict approach (less credential caching) as a starting point, and see if there is a case that more caching wouldn't cause a problem.


问:
Should unit test expected results be hardcoded?
Should the expected results of a unit test be hardcoded, or can they be dependant on initialised variables?  Do hardcoded or calculated results increase the risk of introducing errors in the unit test?  Are there other factors I haven't considered?

For instance, which of these two is a more reliable format?

```<code>[TestMethod]
public void GetPath_Hardcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\fields\\that later\\determine\\a folder";
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}

[TestMethod]
public void GetPath_Softcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\" + string.Join("\\", target.Field1, target.Field2, target.Field3, target.Field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

EDIT 1: In response to DXM's answer, is option 3 a preferred solution?

```<code>[TestMethod]
public void GetPath_Option3()
{
    string field1 = "fields";
    string field2 = "that later";
    string field3 = "determine";
    string field4 = "a folder";
    MyClass target = new MyClass(field1, field2, field3, field4);
    string expected = "C:\\Output Folder\\" + string.Join("\\", field1, field2, field3, field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

答:
I think calculated expected value results in more robust and flexible test cases. Also by using good variable names in the expression that calculate expected result, it is much more clear where the expected result came from in the first place.

Having said that, in your specific example I would NOT trust "Softcoded" method because it uses your SUT (system under test) as the input for your calculations. If there's a bug in MyClass where fields are not properly stored, your test will actually pass because your expected value calculation will use the wrong string just like target.GetPath().

My suggestion would be to calculate expected value where it makes sense, but make sure that the calculation doesn't depend on any code from the SUT itself.

In Response to OP's update to my response:

Yes, based on my knowledge but somewhat limited experience in doing TDD, I would choose option #3.


答:
I'm not actually a big fan of comments. During a software engineering course, I was introduced to the idea of self-documenting code. The code is the only 100% guaranteed correct documentation of itself - comments need to be updated, carefully constructed and relevant, otherwise they are traps that can be worse than no comment. It wasn't until I started working in a C++ shop with a strict style guide and meaningful naming conventions that I truly internalized this concept.

Sometimes comments are necessary. A lot of times, careful variable naming, meaningful use of white space and grouping, and a meaningful logical organization of the code itself eliminates the need for the comment.

This really is a negation of the pretense and validity of your question, as opposed to an answer for the question you had. I still think it is relevant and may help you, and I wasn't a jerk. If not, the -1's will dominate me.

Title: Comment before or after the relevant code

Body:
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.


答:
What if the code was as follows:

```<code>MyTarget() // constructor
{
   Field1 = Field2 = Field3 = Field4 = "";
}
</code>```

Your second example wouldn't catch the bug, but the first example would.

In general, I'd recommend against soft-coding because it may hide bugs. For example:

```<code>string expected = "C:\\Output Folder" + string.Join("\\", target.Field1, target.Field2, target.Field3, target.Field4);
</code>```

Can you spot the problem? You wouldn't make that same mistake in a hard-coded version. It's harder to get the calculations correct than hard-coded values. That's why I prefer to work with hard-coded values than soft-coded ones.

But there are exceptions. What if your code has to run on Windows and Linux? Not only will the path have to be different, it has to use different path separators! Calculating the path using functions that abstract the difference between might make sense in that context.

Title: Should unit test expected results be hardcoded?

Body:
Should the expected results of a unit test be hardcoded, or can they be dependant on initialised variables?  Do hardcoded or calculated results increase the risk of introducing errors in the unit test?  Are there other factors I haven't considered?

For instance, which of these two is a more reliable format?

```<code>[TestMethod]
public void GetPath_Hardcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\fields\\that later\\determine\\a folder";
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}

[TestMethod]
public void GetPath_Softcoded()
{
    MyClass target = new MyClass("fields", "that later", "determine", "a folder");
    string expected = "C:\\Output Folder\\" + string.Join("\\", target.Field1, target.Field2, target.Field3, target.Field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

EDIT 1: In response to DXM's answer, is option 3 a preferred solution?

```<code>[TestMethod]
public void GetPath_Option3()
{
    string field1 = "fields";
    string field2 = "that later";
    string field3 = "determine";
    string field4 = "a folder";
    MyClass target = new MyClass(field1, field2, field3, field4);
    string expected = "C:\\Output Folder\\" + string.Join("\\", field1, field2, field3, field4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

Body:
What if the code was as follows:

MyTarget() // constructor
{
   Field1 = Field2 = Field3 = Field4 = "";
}

Your second example wouldn't catch the bug, but the first example would.

In general, I'd recommend against soft-coding because it may hide bugs. For example:

string expected = "C:\\Output Folder" + string.Join("\\", target.Field1, target.Field2, target.Field3, target.Field4);

Can you spot the problem? You wouldn't make that same mistake in a hard-coded version. It's harder to get the calculations correct than hard-coded values. That's why I prefer to work with hard-coded values than soft-coded ones.

But there are exceptions. What if your code has to run on Windows and Linux? Not only will the path have to be different, it has to use different path separators! Calculating the path using functions that abstract the difference between might make sense in that context.

ContentLicense: CC BY-SA 4.0


答:
In my opinion, both of your suggestions are less than ideal. The ideal way to do it is this one:

```<code>[TestMethod]
public void GetPath_Hardcoded()
{
    const string f1 = "fields"; const string f2 = "that later";
    const string f3 = "determine"; const string f4 = "a folder";

    MyClass target = new MyClass( f1, f2, f3, f4 );
    string expected = "C:\\Output Folder\\" + string.Join("\\", f1, f2, f3, f4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

In other words, the test should work exclusively based on the input and the output of the object, and not based on the internal state of the object. The object should be treated as a black box. (I disregard other issues, like the inappropriateness of using string.Join instead of Path.Combine, because this is just an example.)

Body:
In my opinion, both of your suggestions are less than ideal. The ideal way to do it is this one:

[TestMethod]
public void GetPath_Hardcoded()
{
    const string f1 = "fields"; const string f2 = "that later";
    const string f3 = "determine"; const string f4 = "a folder";

    MyClass target = new MyClass( f1, f2, f3, f4 );
    string expected = "C:\\Output Folder\\" + string.Join("\\", f1, f2, f3, f4);
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}

In other words, the test should work exclusively based on the input and the output of the object, and not based on the internal state of the object. The object should be treated as a black box. (I disregard other issues, like the inappropriateness of using string.Join instead of Path.Combine, because this is just an example.)


问:
How to write a command interpreter/parser?
Problem: Run commands in the form of a string.

command example:

/user/files/ list all;
equivalent to:
/user/files/ ls -la;

another one:

post tw fb "HOW DO YOU STOP THE TICKLE MONSTER?;"

equivalent to:
    post -tf "HOW DO YOU STOP THE TICKLE MONSTER?;"

Current solution:

```<code>tokenize string(string, array);

switch(first item in array) {
    case "command":
        if ( argument1 > stuff) {
           // do the actual work;
        }
}
</code>```

The problems I see in this solution are:

No error checking other than nested ifs-else inside each case. The
script becomes very big and hard to mantain.

Commands and responses are hardcoded.

No way of knowing if flags are correct or missing parameters.

Lack of intelligence to suggest "you might wanted to run $command".

And the last thing I can't address is synonyms in different encodings, example:

```<code>case command:
case command_in_hebrew:
    do stuff;
break;
</code>```

The last one might be trivial, but well, what I want to see is the solid fundations of this kind of program.

I'm currently programming this in PHP but might do it in PERL.

答:
Why dont you simplify a little bit, your requirements ?

Don't use a full parser, its too much complex, and even unnecesary for your case.

Make a loop, write a message that represents yout "prompt", can be the current path you are.

Wait for a string, "parse" the string, and do something depending on the contents of the string.

The string could "parse" like expecting a line, in which spaces are the separators ("tokenizer"), and the rest of characters are grouped.

Example.

The program outputs (and stays in the same line):
/user/files/
The user writes (in the same line)
list all;

Your program will generate a list, collection or array like

```<code>list

all;
</code>```

or, if ";" is considered a separator like spaces

```<code>/user/files/

list

all
</code>```

Your program could start by expecting one single instruction, without unix-style "pipes", neither windowze-style redirection.

Your program could make a dictionary of instructions, each instruction, may have a list of parameters.

The command design pattern applies to your case:

http://en.wikipedia.org/wiki/Command_pattern

This a "plain c" pseudocode, is not tested or finished,
just an idea of how could be done.

You could also make it more object oriented,
and in the programming language, you like.

Example:

```<code>// "global function" pointer type declaration
typedef
  void (*ActionProc) ();

struct Command
{
  char[512] Identifier;
  ActionProc Action;
};

// global var declarations

list<char*> CommandList = new list<char*>();
list<char*> Tokens = new list<char*>();

void Action_ListDirectory()
{
  // code to list directory
} // Action_ListDirectory()

void Action_ChangeDirectory()
{
  // code to change directory
} // Action_ChangeDirectory()

void Action_CreateDirectory()
{
  // code to create new directory
} // Action_CreateDirectory()

void PrepareCommandList()
{
  CommandList->Add("ls", &Action_ListDirectory);
  CommandList->Add("cd", &Action_ChangeDirectory);
  CommandList->Add("mkdir", &Action_CreateDirectory);

  // register more commands
} // void PrepareCommandList()

void interpret(char* args, int *ArgIndex)
{
  char* Separator = " ";
  Tokens = YourSeparateInTokensFunction(args, Separator);

  // "LocateCommand" may be case sensitive
  int AIndex = LocateCommand(CommandList, args[ArgIndex]);
  if (AIndex >= 0)
  {
    // the command

    move to the next parameter
    *ArgIndex = (*ArgIndex + 1);

    // obtain already registered command
    Command = CommandList[AIndex];

    // execute action
    Command.Action();
  }
  else
  {
    puts("some kind of command not found error, or, error syntax");
  }
} // void interpret()

void main(...)
{
  bool CanContinue = false;
  char* Prompt = "c\:>";

  char Buffer[512];

  // which command line parameter string is been processed
  int ArgsIndex = 0;

  PrepareCommandList();

  do
  {
    // display "prompt"
    puts(Prompt);
    // wait for user input
      fgets(Buffer, sizeof(Buffer), stdin);

    interpret(buffer, &ArgsIndex);

  } while (CanContinue);

} // void main()
</code>```

You didn't mention your programming language. You can also mention any programming language, but preferably "XYZ".

Body:
Why dont you simplify a little bit, your requirements ?

Don't use a full parser, its too much complex, and even unnecesary for your case.

Make a loop, write a message that represents yout "prompt", can be the current path you are.

Wait for a string, "parse" the string, and do something depending on the contents of the string.

The string could "parse" like expecting a line, in which spaces are the separators ("tokenizer"), and the rest of characters are grouped.

Example.

The program outputs (and stays in the same line):
/user/files/
The user writes (in the same line)
list all;

Your program will generate a list, collection or array like

list

all;

or, if ";" is considered a separator like spaces

/user/files/

list

all

Your program could start by expecting one single instruction, without unix-style "pipes", neither windowze-style redirection.

Your program could make a dictionary of instructions, each instruction, may have a list of parameters.

The command design pattern applies to your case:

http://en.wikipedia.org/wiki/Command_pattern

This a "plain c" pseudocode, is not tested or finished,
just an idea of how could be done.

You could also make it more object oriented,
and in the programming language, you like.

Example:

// "global function" pointer type declaration
typedef
  void (*ActionProc) ();

struct Command
{
  char[512] Identifier;
  ActionProc Action;
};

// global var declarations

list<char*> CommandList = new list<char*>();
list<char*> Tokens = new list<char*>();

void Action_ListDirectory()
{
  // code to list directory
} // Action_ListDirectory()

void Action_ChangeDirectory()
{
  // code to change directory
} // Action_ChangeDirectory()

void Action_CreateDirectory()
{
  // code to create new directory
} // Action_CreateDirectory()

void PrepareCommandList()
{
  CommandList->Add("ls", &Action_ListDirectory);
  CommandList->Add("cd", &Action_ChangeDirectory);
  CommandList->Add("mkdir", &Action_CreateDirectory);

  // register more commands
} // void PrepareCommandList()

void interpret(char* args, int *ArgIndex)
{
  char* Separator = " ";
  Tokens = YourSeparateInTokensFunction(args, Separator);

  // "LocateCommand" may be case sensitive
  int AIndex = LocateCommand(CommandList, args[ArgIndex]);
  if (AIndex >= 0)
  {
    // the command

    move to the next parameter
    *ArgIndex = (*ArgIndex + 1);

    // obtain already registered command
    Command = CommandList[AIndex];

    // execute action
    Command.Action();
  }
  else
  {
    puts("some kind of command not found error, or, error syntax");
  }
} // void interpret()

void main(...)
{
  bool CanContinue = false;
  char* Prompt = "c\:>";

  char Buffer[512];

  // which command line parameter string is been processed
  int ArgsIndex = 0;

  PrepareCommandList();

  do
  {
    // display "prompt"
    puts(Prompt);
    // wait for user input
      fgets(Buffer, sizeof(Buffer), stdin);

    interpret(buffer, &ArgsIndex);

  } while (CanContinue);

} // void main()

You didn't mention your programming language. You can also mention any programming language, but preferably "XYZ".


答:
Assigning tasks on planning meeting is exactly what goes against just it time decisions and empowering the team. It also goes against sprint agility because since day one in a sprint every developer has exactly aligned what he should do. It also means that every task must be very correctly estimated which is almost never the case.

Imho estimating tasks is redundant. You have committed to set of stories and planning meeting 2 is just enough time to split those stories into tasks and create cards for those tasks (or fill them to some system). There is not enough time to estimate each task and these estimation should not consume time for real development.

Why? Estimation is a garbage. How it can be a garbage? Because doing more estimation will not bring more business value = it is garbage and should be reduced to necessary minimum. The minimum is estimating / sizing stories which helps you to do commitment. Once you did a commitment you don't need any other estimation. You just know that you have fixed date to deliver something you have committed. You will either be able to deliver committed stories or not. Estimating tasks will not help you in that delivery.

Skipping task estimation will in no way affect visibility into sprint progress because the only real measurement of the progress is number of completed stories (story points) and that can be still showed in sprint burn down chart.

Just to make it clear. Commitment means = We will do it. Not we will try to do it or anything other. Yes, you can fail to deliver what you have committed but your commitment should be based on your belief that with your current knowledge you will deliver selected stories. If you have this belief you don't need another estimation.

I always used Scrum in the way where developer choose a new task once he completes his last one. Developers usually say which one they are going to choose on stand-up meeting. Generally there are no rules which task he should choose. It is up to team self-organization and discussion between team members (outside of stand-up meeting). That is postponing decision to the latest possible point where you can react on some changes and problems without affecting your imaginary plan. The task itself can even change the owner if somebody has some problems to complete it - alternatively such task can be developed in pair.

How can pair programming be involved in this? Easily. Team does commitment and team must make it in the way to make space for all development techniques needed to deliver the working increment of the product. Do you estimate a task or task development and task testing? The latter approach is completely wrong. The testing is part of development and in the same way the code review or pairing is part of development if needed.

Doing pair programming should result into completing task faster with smaller amount of bugs and better code quality. It will not be twice as fast so there will be still some overhead but the real impact on commitment caused by occasional pairing should be very small. This is not a case for mentoring or teaching. If you have such developer which needs to be mentored or taught you should not plan his capacity at all for sprints where he learns the product's code base or some technology.

Title: Pair Programming with Scrum

Body:
I'm on a team that is currently using Scrum, and we're considering adding pair programming to help improve the cross-functional skills of the team, as well as help reduce defects with a "two heads are better than one" philosophy.

On our team, each team member typically signs up for a full workload during sprint planning (with "full" being a number that is less than 40 hours a week, allowing for meetings, collaboration, etc.), with a single dedicated owner for each task.  I believe this is fairly common on Scrum teams but may not necessarily be by the book.

In particular, I'm looking to avoid a situation where team members are hesitant to pair because they have their own tasks to work on, which I'm afraid is likely to happen if the team simply self-organizes without time set aside for pairing.

Given this, what is the best way to account for effort/hours/story points in a pairing scenario, to make sure we have appropriately allotted time for pairing?

Some options considered are:

Allow two people to sign up for each task and (roughly) double the number of estimated hours

Only the "hands on keyboard" team member signs up for each task, which is estimated based on that person's estimated hours.  Anyone on the team who will be supporting pairing will sign up for fewer tasks in the sprint to allow time to support pairing.


答:
OK, I'll make the "after" case: the code should always be the primary documentation, while the comment (which has no semantic meaning) is like a parenthetical explanation. So putting the comment below the code that needs explanation leaves the code as the prime explanation, and just uses the comment for clarification. For instance,

```<code>if(date == CHRISTMAS){
     //Deliver presents
     val (nice, naughty) = partition(boysAndGirls);
     prepSled();
     findRudolph();
     putOnRedSuit();
     ...
}else{
     //Not Christmas, build toys
     monitorElves();
     ...
}
</code>```

If you put the comment before the test, the reader is going to tend to read the comment as the primary thing and may not read the code closely, not realizing that they've been misled:

```<code> //Check to see if it's a leap year
 if(year % 4 == 0){ ... }
</code>```

Body:
OK, I'll make the "after" case: the code should always be the primary documentation, while the comment (which has no semantic meaning) is like a parenthetical explanation. So putting the comment below the code that needs explanation leaves the code as the prime explanation, and just uses the comment for clarification. For instance,

if(date == CHRISTMAS){
     //Deliver presents
     val (nice, naughty) = partition(boysAndGirls);
     prepSled();
     findRudolph();
     putOnRedSuit();
     ...
}else{
     //Not Christmas, build toys
     monitorElves();
     ...
}

If you put the comment before the test, the reader is going to tend to read the comment as the primary thing and may not read the code closely, not realizing that they've been misled:

 //Check to see if it's a leap year
 if(year % 4 == 0){ ... }


答:
you have several tasks ahead of you.

looking at your requirements...

You need to parse the command. That's a fairly easy task

You need to have an extensible command language.

You need to have error checking and suggestions.

The extensible command language indicates that a DSL is required. I would suggest not rolling your own but using JSON if your extensions are simple. If they are complex, an s-expression syntax is nice.

Error checking implies that your system also knows about the possible commands. That would be part of the post-command system.

If I was implementing such a system from scratch, I would use Common Lisp with a stripped-down reader.   Each command token would map to a symbol, which would be specified in a s-expression RC file. After tokenization, it would be evaluated/expanded in a limited context, trapping the errors, and any recognizable error patterns would return suggestions. After that, the actual command would be dispatched to the OS.

Title: How to write a command interpreter/parser?

Body:
Problem: Run commands in the form of a string.

command example:

/user/files/ list all;
equivalent to:
/user/files/ ls -la;

another one:

post tw fb "HOW DO YOU STOP THE TICKLE MONSTER?;"

equivalent to:
    post -tf "HOW DO YOU STOP THE TICKLE MONSTER?;"

Current solution:

```<code>tokenize string(string, array);

switch(first item in array) {
    case "command":
        if ( argument1 > stuff) {
           // do the actual work;
        }
}
</code>```

The problems I see in this solution are:

No error checking other than nested ifs-else inside each case. The
script becomes very big and hard to mantain.

Commands and responses are hardcoded.

No way of knowing if flags are correct or missing parameters.

Lack of intelligence to suggest "you might wanted to run $command".

And the last thing I can't address is synonyms in different encodings, example:

```<code>case command:
case command_in_hebrew:
    do stuff;
break;
</code>```

The last one might be trivial, but well, what I want to see is the solid fundations of this kind of program.

I'm currently programming this in PHP but might do it in PERL.


问:
Platform to Learn/Experiment with Web Programming
I am looking to teach myself some web programming, but I am not sure how I can experiment with an actual website. Are there sites that host platforms for these purposes?</p>

答:
"TEST LOCALLY, Host Remotely"

Download something called XAMPP from Apache Friends onto a local Windows box.  This download has EVERYTHING you need to begin playing around with web development on your own local box, and it is ALREADY CONFIGURED PROPERLY BY DEFAULT.  It's trivial to install, and trivial to begin testing/working on your own website!

Then get a good book on PHP for Web development.  Anything on Amazon's top list for PHP would be just fine.  Look for a book that matches your programming skill level, and start hacking away at your own "site", without worrying that you'll mess anything up!

After a while, you'll probably get a neat idea for a "real" website, and after you try it out on your own computer you'll want to push it to "the Internet".  At that point it's just a question of whether you want to go through a free/add-supported hosting company, or a simple/low-cost hosting company.  There are many good ones to chose from!

So I recommend that you install XAMPP from Apache Friends onto a local box, and start programming (today!) in PHP.


问:
Comparison of IDEs for C++ and C development on Linux: KDevelop, Eclipse, NetBeans, CodeBlocks and Anjuta
I'd like to note your experience of full scale IDEs on Linux.

I personally work mostly with vim, however other programmers would like
to see a real IDE. So I'd like to hear your personal opinion about different
IDEs and comparison between them, in following context:

C++ and maybe some C development (not Java, Python and other stuff)

Server side programming (no need for GUI development)

Working on Linux not "cross-platform" development.

Opinion needed regard:

How stable is it? If IDE crashes I don't need it.

Comfortable to use.

Powerful for debugging.

Integration with various build systems

Scalability over huge projects (projects of hundreds thousands of lines of code)

I used to work with KDevelop and it was very nice IDE and seems that KDevelop 4 is a huge progress. It seems also that many rather use Netbeans and Eclipse.

答:
Netbeans is a slow, slow IDE.  We are not using "dinosaur computers", but this IDE HANGS for quite a long time.  If we access the Netbeans IDE over the network (say, using VNC), then forget about it!!! The lag is so bad as to make Netbeans unusable!

I find Eclipse intimidatingly hard to setup for initial use, but if you persevere, you'll wind up with an IDE that has everything you could want or need (possibly by way of plug-ins).

I don't want to use more than one IDE, and I suspect you don't either.  I'd recommend Eclipse, with all its faults.


问:
Software testing automation documentation
What document types could be used when describing software testing automation (on any phase, automation planning, test design, implementation, reporting)? Is there any standard types of documents?
If someone could provide any examples and templates for different types of documents?
What is the difference between manual testing documentation and automated?</p>

答: Did you look at IEEE 829-1998, Standard for Software Test Documentation? I know that in my company the test documents in this standard are used to describe the entire testing strategy. For example, the Master Test Plan will actually include information on testing automation in the approach section.</p>


问:
Generating presentation elements with Javascript vs PHP
What are the pros and cons of generating dynamic pages with javascript vs doing it in PHP?

As an example, I want to display certain records from some database in a table and I'm considering the following approaches:

Use Javascript to get some response in JSON from some PHP page, then dynamically build the table in Javascript.

Write some PHP in the page which will make the query and iterate through the result set echoing the table markup.

What are the pros and cons of each approach?

答:
PHP is rendered on the server.

JavaScript is rendered on the client.

PHP can take direct advantage of all of the commands, scripts, programs, databases (etc) that are available on the server.

JavaScript can not launch any commands, scripts or programs on the client's computer, nor can it access databases (not directly - it needs the data returned to it in some fashion).

I believe that JavaScript is sometimes a clumsy way to program business logic, as it's very hard to isolate your presentation logic from your business logic.

On the other hand you can easily isolate your business logic and presentation logic using PHP as a back-end language, and JavaScript as an aid to the presentation (front-end).

Why not use both?

Kill off as much of the "back-end" work as you can using PHP, then "fix up" any presentation issues using CSS + JavaScript.

Best of both worlds...


答:
Try to comment only where really necessary; the code should try to be self-documenting whenever possible.

That being said, the placement can depend: If you use a separate line for the comment, put it before the actual code. If you have it on the same line, put it after.

```<code>// this workaround is required to make the compiler happy
int i = 0;
</code>```

Vs.

```<code>int i = 0; // make the compiler happy
</code>```

But never:

```<code>int i = 0;
// this workaround is required to make the compiler happy
</code>```

Body:
Try to comment only where really necessary; the code should try to be self-documenting whenever possible.

That being said, the placement can depend: If you use a separate line for the comment, put it before the actual code. If you have it on the same line, put it after.

// this workaround is required to make the compiler happy
int i = 0;

Vs.

int i = 0; // make the compiler happy

But never:

int i = 0;
// this workaround is required to make the compiler happy


问:
Where should date formatting take place in an MVC pattern?
Suppose that you want to show a user list, on a web application having to handle custom date formats (depending on current selected interface language).

Several locations for applying the date format seem possible. Which one would you use, and why?

At model, for example doing a DATE_FORMAT(user.birthdate, '%d/%m/%Y') for date fields (supposing we have a MySQL DB).

At controller level, for example (supposing we use PHP):

```<code>$users = UserModel::getUsers();
// loops through results before display to format dates.
// in the $users structure, we have to know which fields are dates or not
$users = MagicFunctionFormattingDates($users);

$view = new View('someTemplate');
$view->assign('users', $users);
</code>```

At view level, for example (supposing we use a template language such as Smarty):

```<code>{foreach key=keyitem item=row from=$users}
  <tr>
  {foreach key=keyfield item=field from=$row.fields}
     {* Here $field should be an Object or associative array
        holding its 'type' (is it a date or something else) *}
     <td>{MagicFunctionForFormatting field=$field}</td>
  {/foreach}
  </tr>
{/endforeach}
</code>```

A similar and related question goes for sumbitting dates (e.g. on a user registration form). Where should the date conversion take place:

In the controller processing and validating the form, before calling the model?

In the model?

答:
I like handling date presentation (view) and encoding (submit) at the viewer.  I immediately convert it to my desired back-end date format, and stick with that format in the back-end.

One caveat - every "good" back-end system I've developed has been integrated with other systems, necessitating some amount of date conversion in the back-end, as well.  I usually defer that problem to if/when these additional systems need it, and stick with the plan I noted above.


答: If the project is open source, then I don't see a problem posting your findings directly to the mailing list. Particularly if you have a patch already (but even if you didn't). If managed to tell someone about it "privately", as soon as they committed the fix to the repo (which I assume is public as well) everybody would know anyway.</p>

Title: How do I report software vulnerabilities found in an open source library that are widely used but have a dilapidated team structure?

Body:
For most open source project, there is a well-founded project team and corporate sponsorship, and a lot of active contributors. The procedure for filing bug reports are clearly documented.

However, there are also some open source project(s) that have been in existence for more than 10 years (maybe 15), and were included in all sorts of free and commercial products (OSes and linux distros, etc), and everyone just assumes it is correct, despite some parts of it in a state of despair and full of bugs.

It appears to me that the real users (programmers in-the-know) simply choose to use the library in a certain way as not to trigger the bug. Few choose to speak up.

There are also big-name companies that fix the bugs quietly (in their own products) without giving out any patches. And use that to their business advantage.

There is no leading developer. There is no information as to who are the active developers, except that you can browse the mailing list and see who has recently submitted patches, and assume that they might know someone who is helpful.

How should I handle a vulnerability case, without leaking information in a way that gives ammunition to the bad guys?

This question is a spin-off from: https://softwareengineering.stackexchange.com/questions/5168/whats-the-biggest-software-security-vulnerabilty-youve-personally-discovered


问:
What would be an appropriate algorithm to factorise numbers in the range of a few billion?
I'm learning Python at the moment and to give me reasons to apply what i'm learning I'm having a crack at some of the problems on Project Euler

I'm currently on number 3, which is to determine the highest prime factor of said number.

I've deduced I need to probably have two algorithms, one to determine primality, and the second which would involve finding factors of the number.

So i've been reading up on Wiki articles. Trying to determine what might be the best algorithm to use and how to go about it.

But it's been a while since i've done some hardcore maths based programming and i'm struggling to start somewhere.

I was looking at using Fermat's factorization method with inclusion of Trial by Division but I don't want to make something too complicated I'm not after to crack RSA I just want two algorithsm suitable for my problem and there in lies my question.

What algorithms would you use for testing for primality / factoring a number that are suitable to the problem at hand?

Edit

Thank you all for your answers and insights they have been most helpful I upvoted all that were useful either through advice or through there own Euler experiences. The one I marked as right was simply the most useful as It gave me a proper place to start from which was a push in the right direction. Thanks again =)

答:
As there's already one complete solution, I'll post this Haskell one...

```<code>--  Problem is to find the largest prime factor of 600851475143
module Factor (testval, bigfactor) where
  testval = 600851475143

  bf' :: Integer -> Integer -> Integer

  bf' f x | (f == x)         = f
          | ((mod x f) == 0) = bf' f (div x f)
          | True             = bf' (f+1) x

  bigfactor :: Integer -> Integer

  bigfactor x | (x <  1) = error "Parameter less than 1"
              | (x == 1) = 1
              | True     = bf' 2 x
</code>```

Basically, there's no need to test for primality. If you divide out the factors you find (and make sure you handle repeating factors), then a non-prime factor can never occur, because a non-prime factor is a product of smaller prime factors.

Loaded and ran this with GHCi - it's instant, and I've now got a grand total of 4 (yes, four!) Euler problems solved.

Body:
As there's already one complete solution, I'll post this Haskell one...

--  Problem is to find the largest prime factor of 600851475143
module Factor (testval, bigfactor) where
  testval = 600851475143

  bf' :: Integer -> Integer -> Integer

  bf' f x | (f == x)         = f
          | ((mod x f) == 0) = bf' f (div x f)
          | True             = bf' (f+1) x

  bigfactor :: Integer -> Integer

  bigfactor x | (x <  1) = error "Parameter less than 1"
              | (x == 1) = 1
              | True     = bf' 2 x

Basically, there's no need to test for primality. If you divide out the factors you find (and make sure you handle repeating factors), then a non-prime factor can never occur, because a non-prime factor is a product of smaller prime factors.

Loaded and ran this with GHCi - it's instant, and I've now got a grand total of 4 (yes, four!) Euler problems solved.


问:
Is it considered bad practice to have PHP in your JavaScript
So many times on this site I see people trying to do things like this :

```<code><script type="text/javascript">
  $(document).ready(function(){

     $('<?php echo $divID ?>').click(funtion(){
       alert('do something');
     });

  });
</script>
</code>```

I don't think that this is some sort of pattern that people naturally fall into. There must be some sort of tutorial or learning material out there that is showing this, otherwise we wouldn't see it so much. What I'm asking is, am I making too big a deal of this or is this a really bad practice?

EDIT :
Was speaking to a friend of mine about this who often puts ruby in his JavaScript and he brought up this point.

Is it ok to dynamically place application wide constants in your JavaScript so you don't have to edit two files. for example...

```<code>MYAPP.constants = <php echo json_encode($constants) ?>;
</code>```

also is it OK to directly encode data you plan to use in a library

```<code>ChartLibrary.datapoints = <php echo json_encode($chartData) ?>;
</code>```

or should we make an AJAX call every time?

答: I don't think this is bad practice. If the ID required in your JavaScript is dynamic there is no other way to do this.</p>

OwnerDisplayName: Greg Guida

OwnerDisplayName: ZombieHunter


答:
The only thing I can think off that can really cause issues is when PHP errors are set to be displayed and so it shoves a load of HTML showing the PHP error into your JavaScript.

Also because its it in script it therefore doesn't show and it can sometimes take a while to realize why your script is broken.

Title: Is it considered bad practice to have PHP in your JavaScript

Body:
So many times on this site I see people trying to do things like this :

```<code><script type="text/javascript">
  $(document).ready(function(){

     $('<?php echo $divID ?>').click(funtion(){
       alert('do something');
     });

  });
</script>
</code>```

I don't think that this is some sort of pattern that people naturally fall into. There must be some sort of tutorial or learning material out there that is showing this, otherwise we wouldn't see it so much. What I'm asking is, am I making too big a deal of this or is this a really bad practice?

EDIT :
Was speaking to a friend of mine about this who often puts ruby in his JavaScript and he brought up this point.

Is it ok to dynamically place application wide constants in your JavaScript so you don't have to edit two files. for example...

```<code>MYAPP.constants = <php echo json_encode($constants) ?>;
</code>```

also is it OK to directly encode data you plan to use in a library

```<code>ChartLibrary.datapoints = <php echo json_encode($chartData) ?>;
</code>```

or should we make an AJAX call every time?

OwnerDisplayName: Alex Coplan


答:
The biggest problem with your snippet is you're missing the # to make it a valid jQuery selector ;).

I would say you should try avoid including PHP in your JavaScript where possible. What's wrong with changing the selector in your click() handler to a class, and adding the class to the element in question if you want the handler to be fired, and not if you don't;

```<code><script type="text/javascript">
  $(document).ready(function(){

     $('.foo').click(funtion(){
       alert('do something');
     });

  });
</script>

<div id="bar" class="<?php echo ($someCond ? 'foo' : ''); ?>">Hello</div>
</code>```

There are circumstances where you need to include PHP in your JavaScript; but I must admit these are few and far between.

Once example is when you have different environments; test, staging and live. Each of them have a different location of your assets (images, mainly). The easiest way to set the path so that it can be used by JavaScript is something like;

```<code>var config = { assets: "<?php echo $yourConfig['asset_url']; ?>" };
</code>```

Body:
The biggest problem with your snippet is you're missing the # to make it a valid jQuery selector ;).

I would say you should try avoid including PHP in your JavaScript where possible. What's wrong with changing the selector in your click() handler to a class, and adding the class to the element in question if you want the handler to be fired, and not if you don't;

<script type="text/javascript">
  $(document).ready(function(){

     $('.foo').click(funtion(){
       alert('do something');
     });

  });
</script>

<div id="bar" class="<?php echo ($someCond ? 'foo' : ''); ?>">Hello</div>

There are circumstances where you need to include PHP in your JavaScript; but I must admit these are few and far between.

Once example is when you have different environments; test, staging and live. Each of them have a different location of your assets (images, mainly). The easiest way to set the path so that it can be used by JavaScript is something like;

var config = { assets: "<?php echo $yourConfig['asset_url']; ?>" };

OwnerDisplayName: Matt


答:
This is a bad practice in my opinion, as you would need to call this file something.php and then you couldn't compress it for example, not mentioning it isn't ok to mix in your server stuff with your JavaScript. Try to limit the mixing between PHP and JS as much as possible.

You can always do this instead:

```<code>function setOnClick(divid) {
 $(divid).click(funtion(){
   alert('do something');
 });
}
</code>```

And then you could call this function in a php file, to make these mixing things as small as possible.

```<code>$(function() {
  setOnClick('<?php echo $divId; ?>');
});
</code>```

By doing this (having bigger JS files, not 2-3 lines where it doesn't matter) you can take advantage of compressing the JS file and front-end developers feel much comfortable working only with JavaScript in my opinion (as you could write Python, Ruby etc not only PHP - and the code could get bigger and bigger depending on what you need to do there).

Body:
This is a bad practice in my opinion, as you would need to call this file something.php and then you couldn't compress it for example, not mentioning it isn't ok to mix in your server stuff with your JavaScript. Try to limit the mixing between PHP and JS as much as possible.

You can always do this instead:

function setOnClick(divid) {
 $(divid).click(funtion(){
   alert('do something');
 });
}

And then you could call this function in a php file, to make these mixing things as small as possible.

$(function() {
  setOnClick('<?php echo $divId; ?>');
});

By doing this (having bigger JS files, not 2-3 lines where it doesn't matter) you can take advantage of compressing the JS file and front-end developers feel much comfortable working only with JavaScript in my opinion (as you could write Python, Ruby etc not only PHP - and the code could get bigger and bigger depending on what you need to do there).

OwnerDisplayName: alessioalex


答:
It depends by whom, and if you ask me, yes I do consider it back practice for a few reasons.  First of all, I'd prefer to have javascript code in its own JS file that the php parser would not be able to touch.

Secondly, php executes at server time only, so if you are depending on some variable in php to change your javascript, that may not work very well.  If there is some page-load setting you want to control with javascript, I typically prefer to add that value to the DOM with php so that javascript can reach it when and if it wants to (in a hidden div, for example).

Finally, just for organizational purposes, this can get very annoying.  It's bad enough to mix html and php (in my opinion).

OwnerDisplayName: tandu


答:
Some people would argue that it's bad practice.
Not because it's PHP inside JS, but because it's inline JS and so won't be cached by the browser for ease of loading the next time.

IMO it's always better to use JSON to pass variables between the 2 languages, but I guess it's up to you.

OwnerDisplayName: Nick


答:
Typically, it is bad practice to use language X to generate code in language Y.

Try decoupling the two languages by making data their only interface -- don't mingle the code.

In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:

```<code><script type="text/javascript">
  var cfg = {
    theId: "<?php echo $divID ?>",
    ...
  };

  $(document).ready(function(){
     $("#" + cfg.theId).click(funtion(){
       alert('do something');
     });
  });
</script>
</code>```

This way, PHP only cares about populating the data structure and JavaScript only cares about consuming the data structure.

This decoupling also leads the way to loading the data asynchronously (JSON) in the future.

Update:

To answer the additional questions you asked with your update, yes, it would be good practice to apply the DRY principle and let PHP and JavaScript share the same configuration object:

```<code><script type="text/javascript">
  var cfg = <?php echo json_encode($cfg) ?>;

  ...
</code>```

There is no harm in inserting the JSON representation of your configuration directly into your page like this. You don't necessarily have to fetch it via XHR.

Body:
Typically, it is bad practice to use language X to generate code in language Y.

Try decoupling the two languages by making data their only interface -- don't mingle the code.

In your example, you could improve the code by using PHP to populate a cfg structure that's available to JavaScript:

<script type="text/javascript">
  var cfg = {
    theId: "<?php echo $divID ?>",
    ...
  };

  $(document).ready(function(){
     $("#" + cfg.theId).click(funtion(){
       alert('do something');
     });
  });
</script>

This way, PHP only cares about populating the data structure and JavaScript only cares about consuming the data structure.

This decoupling also leads the way to loading the data asynchronously (JSON) in the future.

Update:

To answer the additional questions you asked with your update, yes, it would be good practice to apply the DRY principle and let PHP and JavaScript share the same configuration object:

<script type="text/javascript">
  var cfg = <?php echo json_encode($cfg) ?>;

  ...

There is no harm in inserting the JSON representation of your configuration directly into your page like this. You don't necessarily have to fetch it via XHR.

OwnerDisplayName: Ates Goral


答:
Report the bug and if noone cares then clone the repository on github and fix the error there, and point to that repository in the original bugreport so others can get a fixed version.

Remember to merge the clone regularily to pick up other fixes.


答:
Dynamically generated JavaScript is a horrible, bad practice.

What you're supposed to do is comprehend what Seperation of Concerns and Progressive Enhancement mean.

This basically means you have dynamic HTML and static JavaScript (which enhances the HTML).

In your case you probably want a class on your div and select it with a class selector

OwnerDisplayName: Raynos


答:
I think others already provided good answers but I'll add mine only because I think your team just transitioned to Scrum and now you guys are in a very similar position we were when we started.

First off, our introduction to Agile and more specifically Scrum wasn't very smooth. Basically management came down and said, from this day forth you shall do Scrum and this is a process you will all follow. So much for People over Process.

The process we originally followed (blindly, I might add) ended up very similar to how you described. People get assigned tasks, everyone gets booked and we all go back to our desks and plug away. Then we have a boring stand-up meeting every day.

The key to realize is that Agile, and Scrum included, is actually about people. When the team goes into iteration planning, don't let your Scrum master (who is probably your manager) to assign you hours, stories and tasks.  It is completely UP TO THE TEAM. I think for a lot of people this is a very hard concept to get through because for years before that they'd come to work and they would have a boss (manager, technical lead...) who would simply assign work.  They dive into Scrum but everyone (including scrum master himself) continues to operation in the same mode.

One day, you'll get sick of this, so you'll start reading books, blogs and keep asking questions like this on stack exchange.  The realization that you will get is that you as the developer and your teammates should be the driving force behind committing to stories and assigning tasks.  If you guys feel you will benefit from pair programming, by all means create a 2 tasks for each of the engineers and assign both of them hours.  The only thing scrum master should be doing is measuring velocity against completed stories that you delivered AS A TEAM in the previous iteration.

Also another thing that bugs the crap out of me is how people are told that their capacity IS ALWAYS 75% of total hours, so that's what they commit to and then for the entire duration of the iteration they complain that a) they can't help you or b) they can't do the right thing because they've been assigned too many hours.  People should not be told how many hours to commit and they certainly should push back if scrum master is attempting to pull something like this!  Everyone should commit to exactly what they are comfortable with.  For example, I'm a team lead and frequently I'd end up in a random unplanned design discussion, or helping someone with code, or with troubleshooting weird stuff, so my capacity is never above 50%.

It took our team 4 release cycles to learn not to do the things I just mentioned and even though we've definitely improved, if you ask the experts we are not even half agile. So still a lot of learning to do.

Update 1: Response to Cliff's comment
Well you offered your ears so here it is...

You are right, cultural shift is key, but this shift doesn't need to happen at the executive level. Your own group manager can change the culture within your team and isolate you guys from corporate BS that he has to deal with. What you are describing was EXACTLY us about from 2007 to 2010.  Our team (and other teams as well) flopped release after release.  In one of the releases using management's "process for being agile" we manage to have 9 people produce the work that would usually be done by a single person and it took us double the time.  I had so much free time, that I even updated my resume.

Then, I had a conversation with my boss and explained all these things to him how agile is about people and that if you want us to care about the product, let us make decisions that affect how we work on and deliver the product.  I think he decided to make it an experiment out of it, he made every single change we... well, mostly myself, but I talk with the rest of the team a lot, hence 50% capacity :) ... proposed. It's possible that he figured that if he makes all the changes we are asking for and we still fail, he'll come back with a victorious "I told you so".

So in the last 12 months, we've eliminated so much "stupid" it's not even funny. Our stand-up meetings actually make sense now because we work together, not in isolation. We still have ownership (at least for now) of specific parts of the product, but we also cross very frequently into each others' code.  We constantly do code reviews so that not only team members learn other code, but they also learn better coding and design techniques.  We've broken monolithic, giant "agile" team into 3 different teams so planning and other meetings are much shorter and people actually care about them because they don't sit around and listen about things they don't care about. I've seen nights when 4 out of 5 of our guys (one of the teams) would be online at 11pm at night and nobody actually told us we have to work hard or ever pressured us to work over 40 hours. People who couldn't care less half a year ago, all of a sudden are engaged and excited about the work they are doing. And all it took was for our manager to do was say, "you guys decide what is right and do what you need to do and I'll keep corporate BS out of the team as much as I can."

It started as experiment (my suspicion, he never told me that), but now our group is kicking butt compared to other development groups in the department and we even have other developers who are now trying to come over and join us.

The biggest hurdle for us ever since this change happened (and still a problem today) was the fact that engineers in normal corporate environment are like experimental mice in a cage. Even when your manager decides to go truly "agile" and removes the cage, everyone has been in that cage for so long, they don't even realize they are free. So even with all the freedom, they continue acting as if they are still constrained. I think what would help is to have at least few people on the team (such as yourself), who go outside the boundaries of the group and seek out better ways of doing things.  Then come back into that group and stir it up a little.

In your case, maybe paired programming isn't a solution if you are looking for another external force to come down onto the team and tell them how to work. Instead, throw the rules out, sit down with them, without management, and ask them what they want to do? What will make them happy? Productive? Identify the biggest problems and then ask THE TEAM what they think solution should be.

Title: Pair Programming with Scrum


答:
Here is what i would propose:

1. Test strategy document:

This outlines the over all testing objectives, what testing goals exists and how is the over all testing will be performed linking all levels from unit test, component test, system test and integration test. This is not a standard or something - but it can be something of this sort.

2. Test suit:

This is the collection of test cases and conditions on when and how each cases needs to be performed. Each set of inputs, procedures and expected output behavior against each elements. There are times when more than just success and failures are noted so that further analysis is done on this.

3. Test environment/setup and procedures

If you are automating the testing process fully or partly, it is worthwhile to document how exactly the (various elements of) testing is going to get executed. It should be debated and validated if the testing performed here is correct method or not. The developer and QA associated should know how to operate the set of tools and what procedures to follow.

4. Traceability Matrix:

This is a well defined matrix which identifies which set of test cases are relevant to promise each functionality point is assured to be steady. Read more here or this wiki link.
Whenever a new bug is discovered or a new feature is requested, traceability matrix should be updated to capture these changes.

5. Test results

Whether generated automated or performed manually, the results (detailed and summerised) should be captured in a test execution sheet. Most important thing to note down is that
a. original observation (such as logs, actual output of the application) should be capture as relevant so that conclusions can be validate.
b. the document needs to capture the build against which these test were carried out; different build may not produce the same behavior against the same test.

Procedure and formats can be developed as needed. Most important thing, from my personal experience is that instead of making water tight compliance to some format allow people do document this like a running diary making only few things mandatory and let people pour in more information freely. Testing is never static (at least for any reasonably complex project) so over time all these template must evolve continuously - quite often every next step could be a major departure from the last one. If either the templates are stale, or people do not follow that because it is too rigid, eventually much of the relevant knowledge through testing procedure won't be reflected right.

Title: Software testing automation documentation

Body:
What document types could be used when describing software testing automation (on any phase, automation planning, test design, implementation, reporting)? Is there any standard types of documents?
If someone could provide any examples and templates for different types of documents?
What is the difference between manual testing documentation and automated?</p>


答:
There are two aspects in the discussion:

1. Using the target itself for test case

The first question is should/can you use the class itself to rely and get part of the work done in the test stub? - The answer is NO since, in general, you should never make assumption about the code which you are testing. If this is not done properly, over time bugs become immune to some unit testing.

2. Hardcoding

should you hard code? Again the answer is No. because like any software - the hard coding of he information becomes difficult when things evolve. For example, when you want the above path to be modified again, you need to either write additional unit or keep modifying. A better method is to keep input and evaluation date derived from the separate configuration that can be easily adapted.

for example here is how i would right the test stub.

```<code>[TestMethod]
public void GetPath_Tested(int CaseId)
{
    testParams = GetTestConfig(caseID,"testConfig.txt"); // some wrapper that does read line and chops the field.
    MyClass target = new MyClass(testParams.field1, testParams.field2);
    string expected = testParams.field5;
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}
</code>```

Body:
There are two aspects in the discussion:

1. Using the target itself for test case

The first question is should/can you use the class itself to rely and get part of the work done in the test stub? - The answer is NO since, in general, you should never make assumption about the code which you are testing. If this is not done properly, over time bugs become immune to some unit testing.

2. Hardcoding

should you hard code? Again the answer is No. because like any software - the hard coding of he information becomes difficult when things evolve. For example, when you want the above path to be modified again, you need to either write additional unit or keep modifying. A better method is to keep input and evaluation date derived from the separate configuration that can be easily adapted.

for example here is how i would right the test stub.

[TestMethod]
public void GetPath_Tested(int CaseId)
{
    testParams = GetTestConfig(caseID,"testConfig.txt"); // some wrapper that does read line and chops the field.
    MyClass target = new MyClass(testParams.field1, testParams.field2);
    string expected = testParams.field5;
    string actual = target.GetPath();
    Assert.AreEqual(expected, actual,
        "GetPath should return a full directory path based on its fields.");
}


答:
Several locations for applying the date format seem possible. Which one would you use, and why?

The view, because text formatting is view-related.

A similar and related question goes for submitting dates (e.g. on a user registration form). Where should the date conversion take place?

The model, via an appropriate setter method.

Title: Where should date formatting take place in an MVC pattern?

Body:
Suppose that you want to show a user list, on a web application having to handle custom date formats (depending on current selected interface language).

Several locations for applying the date format seem possible. Which one would you use, and why?

At model, for example doing a DATE_FORMAT(user.birthdate, '%d/%m/%Y') for date fields (supposing we have a MySQL DB).

At controller level, for example (supposing we use PHP):

```<code>$users = UserModel::getUsers();
// loops through results before display to format dates.
// in the $users structure, we have to know which fields are dates or not
$users = MagicFunctionFormattingDates($users);

$view = new View('someTemplate');
$view->assign('users', $users);
</code>```

At view level, for example (supposing we use a template language such as Smarty):

```<code>{foreach key=keyitem item=row from=$users}
  <tr>
  {foreach key=keyfield item=field from=$row.fields}
     {* Here $field should be an Object or associative array
        holding its 'type' (is it a date or something else) *}
     <td>{MagicFunctionForFormatting field=$field}</td>
  {/foreach}
  </tr>
{/endforeach}
</code>```

A similar and related question goes for sumbitting dates (e.g. on a user registration form). Where should the date conversion take place:

In the controller processing and validating the form, before calling the model?

In the model?