问:
Service layer vs DAO -- Why both?
I have been working with SpringMVC, Hibernate, and some databases in a java web application example.

There are a few different ones that do this, but this Spring 3 and hibernate integration tutorial with example has a model class, view (in jsp), and a service and dao classes for the controller.

My question is, don't both the service and DAO classes do the same thing? Why would you need them both?

This was the tutorial I was actually using: http://fruzenshtein.com/spring-mvc-security-mysql-hibernate/

答:
I am the writer of post in question. I have got my fair share of working on different technologies and different architectures.

Based on above, I can safely say that having Service layer and DAO layer is always a good idea.

DAO should be limited to only remove/update/insert/select Entity objects into/from database and that's all. If you want to do anything extra in terms of logic, add it to Service layer. This will help in making code modular and easily replaceable when database is replaced (for some part of data). This is specially applicable in applications involving reports which have heavy logics even after fetching data from database.

Also, in Spring, security is applied at service layer ideally. You would not like to change this way.

Title: Service layer vs DAO -- Why both?


问:
Is short-circuit evaluation a consequence of call-by-name?
If the boolean operators &&, || are implemented as infix methods, then isn't short-circuit evaluation just a consequence of being implemented using call-by-name semantics, since, for example, the && method wouldn't then evaluate the second arg in any case if the first is false.

I'm just wondering because they are generally treated as separate topics (e.g in the Scala intro course I'm taking - https://class.coursera.org/progfun-003/lecture/5 ) but short-circuit evaluation seems to just be a consequence of call-by-name.

答:
Turns out Martin answers the exact question 15 minutes later on in the same video! Yes, short-circuit evaluation is implemented using call by-name args. Martin discusses just this and defines the and function as follows:

```<code>  def and(x:Boolean, y: => Boolean) {
    if (x) y else false
  }
</code>```

Note that if the second arg y was not call-by-name, then and(false,<infinite loop expr>) would not terminate, whereas we would expect it to return false due to short-circuit eval.

ContentLicense: CC BY-SA 3.0

Body:
Turns out Martin answers the exact question 15 minutes later on in the same video! Yes, short-circuit evaluation is implemented using call by-name args. Martin discusses just this and defines the and function as follows:

  def and(x:Boolean, y: => Boolean) {
    if (x) y else false
  }

Note that if the second arg y was not call-by-name, then and(false,<infinite loop expr>) would not terminate, whereas we would expect it to return false due to short-circuit eval.


问:
Contract Based Programming vs Unit Test
I am a somewhat defensive programmer and a big fan of Microsofts Code Contracts.

Now I cannot always use C# and in most languages the only tool I have is assertions. So I usually end up with code like this:

```<code>class
{
    function()
    {
         checkInvariants();
         assert(/* requirement */);

         try
         {
             /* implementation */
         }
         catch(...)
         {
              assert(/* exceptional ensures */);
         }
         finally
         {
              assert(/* ensures */);
              checkInvariants();
         }
    }

    void checkInvariants()
    {
         assert(/* invariant */);
    }
}
</code>```

However, this paradigm (or whatever you would call it) leads to a lot of code cluttering.

I have started to wonder if it is really worth the effort and whether proper unit test would already cover this?

答:
In addition to unit tests and code contracts, I just thought I'd highlight another aspect, which is the value in defining your interfaces such that you eliminate or reduce the possibility of calling your code incorrectly in the first place.

It's not always easy or possible, but definitely worth asking yourself the question, "Can I make this code more foolproof?"

Anders Hejlsberg, creator of C#, said that one of the biggest mistakes in C# was not including non-nullable reference types. It's one of the main reasons so much necessary guard code clutter exists.

Still, refactoring to only have the necessary and sufficient amount of guard code makes for, in my experience, more usable and maintainable code.

Agree with @duros on the rest of it.

Title: Contract Based Programming vs Unit Test


问:
Unit (regression) testing scientific algorithms given floating point behavior
I have been working on a project and running into a very difficult problem.
The problem can be stated simply as how to unit-test numerical algorithms.
However if you just took this simple statement you would get the standard set of answer isolation of input, random processes, mocking, tolerancing, etc.

The answer (if there is one) does not reside with these.

Also, as a note, I am not concerned with testing the correctness of the algorithm.  That is done with very different methods and it is assumed that the algorithm is correct.  What I am using unit-testing for is to make sure that changes in other parts of the system/support algorithms do not change the output of the algorithm under test.

So, for a description of the problem:
We have an algorithm which takes Gigabits of data, processing it, and generates an image with a corresponding map of which pixels are good and which ones are not.  It is this map which I need to verify does not change and pixels which are not valid are not to be used in any way other than the fact that they invalid.

If this was all that was given I would have many possible solutions and in fact the method have been using for years is to look at the number of valid pixels, the average, standard deviation, peak and valley of the image.  This has proven very sensitive detector for changes.

But, this year has added complications which is causing issues with this approach.

The number of threads being used has increased causing changes in the floating point behavior.  In the past the smaller number of thread was accounted for in the tolerances used.

We have been using floating point (as compared to double) to increase throughput.  This has caused the rounding behavior to change even more and combined with the number of threads makes it worse.  This has also been made worse as we move to using SIMD processing like GPU and/or AVX instructions sets.

We have been enhancing the algorithms used to recover more of the pixels which would have been marked as invalid in the past are not valid.  This combined with 1 and 2 above is resulting in some pixels being included on some machine and not on others.  Since these are on the edge of useability these difference are handled by the algorithms with use this image and are not of concern for the system as a whole, but are causing problems with unit testing the algorithms.

We have also recently ran into the problem that two numbers (internal to the calculation) are the same and because of the rounding behavior one or the other is picked resulting in different outputs.  .  Again this is not a problem of the system as a whole, only with unit testing to flag for differences.

As a minor side example, we also have other non-linear algorithms with due to rounding behavior can give different outputs.  Since these algorithms are self correcting the final solution is good, but has a higher variability than easily accounted for unless the tolerances are opened larger than desired.

So, my questions is how to account for these issue in unit testing.

I strongly need unit testing because we have a team of programmers working on the system and we need the ability to detect when someone makes a change which unknowingly impacts other algorithms.  Yes this has happened in the past and the method being used at the time caught the change before it reached the final product.  As the primary algorithm developer I can use your help.  I have had many ideas, but they don’t work for all cases and it’s not clear when to use one of the different methods.

Edit: I now that this is frequently called regression testing but I also know that many time it is also generically called unit testing by many people, even if it's not completely correct.

I am not necessarily looking for a magic bullet (that would be nice) but I do need a way of handling these issues in a way which can be handled by others in the group which may not be as knowledgeable on the details.  If that is a “pick” one of these methods that is fine if it the rule are clear.  We do adjust the parameters when we change the algorithms, but once it is fixed the floating point behavior is still causing differences.  When we see differences we always investigate why and in general we try to adjust the algorithm to reduce the difference, but there are times where these is not possible because of the additional computation time.  If we stayed away from the limits this would not be an issue (as in the past) but to advance the technology we need to push the limits giving rise to the issues described.

You can see this in a simple example. Calculating an average of many numbers.  If you stay with number which are close to each other, there are simple methods to make sure the results are accurate.  Now when you allow for numbers which have large (orders of mag) difference, with threading, float compared to double, etc you can get very different results. Yes I know there are algorithms which can be used to fix these issue but they can be very computation expensive. While averaging is not my problem you could imagine that the difference don’t impact downstream processing but you still want to write a test to monitor the calculation.

答:
How do you eat an elephant? One bite at a time. It sounds you are looking for a "magic bullet" to solve all of your problems at once, and that's IMHO part of the problem. There is not magic bullet, this is hard work, and you can only solve it step-by-step.

For example, you told us that you have already some fuzzy or statistical methods in place to compare the result of your tests to an expected result. I guess these fuzzy methods have some threshold parameters when to accept a result and when not. Whenever you change the behaviour of your algorithms, you will have to adept these parameters - do this for one change after another, run the tests again, make sure the new results are in the accepted range. In fact, you have to fine-tune this parameters, since it may be not ad-hoc clear which results are correct, which are incorrect and if there is a "grey area" between right and wrong.

If that does not work, you may have to look for a modification of the "fuzzy comparison" itself - each time you come across a new kind of change. Unfortunately I cannot tell you how these comparison have to look like, since one must have in-depth know-how about your problem domain to make a right decision.

EDIT: maybe image matching techniques will help in your case, see this SO post for some ideas.

And if this does not work either, this may also be a sign that your modification of the algorithm introduced too many unwanted side effects, so maybe you don't have to change the test, but the way you modify the algorithm implementation.

I have had many ideas, but they don’t work for all cases

Then don't look for a solution which works for "all cases". Use different solutions for different test cases.


答: Do both, but make some static helper methods to clarify your intentions. This is what Google did for Java, check out code.google.com/p/guava-libraries/wiki/PreconditionsExplained</p>

Title: Contract Based Programming vs Unit Test

Body:
I am a somewhat defensive programmer and a big fan of Microsofts Code Contracts.

Now I cannot always use C# and in most languages the only tool I have is assertions. So I usually end up with code like this:

```<code>class
{
    function()
    {
         checkInvariants();
         assert(/* requirement */);

         try
         {
             /* implementation */
         }
         catch(...)
         {
              assert(/* exceptional ensures */);
         }
         finally
         {
              assert(/* ensures */);
              checkInvariants();
         }
    }

    void checkInvariants()
    {
         assert(/* invariant */);
    }
}
</code>```

However, this paradigm (or whatever you would call it) leads to a lot of code cluttering.

I have started to wonder if it is really worth the effort and whether proper unit test would already cover this?


答: I wouldn't say that it's a consequence. It is however a requirement.</p>

Title: Is short-circuit evaluation a consequence of call-by-name?

Body:
If the boolean operators &&, || are implemented as infix methods, then isn't short-circuit evaluation just a consequence of being implemented using call-by-name semantics, since, for example, the && method wouldn't then evaluate the second arg in any case if the first is false.

I'm just wondering because they are generally treated as separate topics (e.g in the Scala intro course I'm taking - https://class.coursera.org/progfun-003/lecture/5 ) but short-circuit evaluation seems to just be a consequence of call-by-name.


问:
What if I have no good ideas to implement a feature?
I'm working on my own application and I'm stuck.  I have to implement a feature but I can't find a good approach to implement this feature.  I was thinking about it for a couple of days, and no good thoughts came. Searching the Internet didn't give me any inspiration.

I need to move on, but I want to know, what's the best:

Think more, wait more, and keep on searching for the best approach

Stop wasting time and start with poor design, covering everything with tests

What do you think? As I said before, I'm working on my own application. I don't have any deadlines, but I also want to finish coding the app asap.

答: What about asking another person? For example, you could describe your problem here, or, if it is more an implementation issue, on stackoverflow.com, and ask for ideas. Sometimes it will already help you if you start writing down the problem, even if you don't get good answers.</p>


答:
If searching fails, you could always implement using the first (not necessarily the best) idea you got, and then refactor it later when you find the right approach.

This is the right approach, since even if you find something that looks like a good idea, it may turn out to be bad later on. Or it may be good at that time, but later you find something much better. Then you'll still have to refactor.

When doing this, make sure to design and implement in such way that it is easy to refactor. If you do it properly, you'll have to change only the problematic part, and not start from start.

Title: What if I have no good ideas to implement a feature?

Body:
I'm working on my own application and I'm stuck.  I have to implement a feature but I can't find a good approach to implement this feature.  I was thinking about it for a couple of days, and no good thoughts came. Searching the Internet didn't give me any inspiration.

I need to move on, but I want to know, what's the best:

Think more, wait more, and keep on searching for the best approach

Stop wasting time and start with poor design, covering everything with tests

What do you think? As I said before, I'm working on my own application. I don't have any deadlines, but I also want to finish coding the app asap.


答:
There is a contradiction in your question. First you are saying:

What I am using unit-testing for is to make sure that changes in other parts of the system/support algorithms do not change the output of the algorithm under test.

But then you list several ways the output has changed that were not the changes you wanted to catch. So "change of the output" isn't your ultimate deciding criterion, but you are using it in your unit test. Why?

You need to define which changes are meaningful to you (as the "any change" metric clearly doesn't work) and use that in your unit tests.

On the other hand, maybe you'd like to be notified for any change, but need a quicker method to approve the new results than editing source code?

Title: Unit (regression) testing scientific algorithms given floating point behavior

Body:
I have been working on a project and running into a very difficult problem.
The problem can be stated simply as how to unit-test numerical algorithms.
However if you just took this simple statement you would get the standard set of answer isolation of input, random processes, mocking, tolerancing, etc.

The answer (if there is one) does not reside with these.

Also, as a note, I am not concerned with testing the correctness of the algorithm.  That is done with very different methods and it is assumed that the algorithm is correct.  What I am using unit-testing for is to make sure that changes in other parts of the system/support algorithms do not change the output of the algorithm under test.

So, for a description of the problem:
We have an algorithm which takes Gigabits of data, processing it, and generates an image with a corresponding map of which pixels are good and which ones are not.  It is this map which I need to verify does not change and pixels which are not valid are not to be used in any way other than the fact that they invalid.

If this was all that was given I would have many possible solutions and in fact the method have been using for years is to look at the number of valid pixels, the average, standard deviation, peak and valley of the image.  This has proven very sensitive detector for changes.

But, this year has added complications which is causing issues with this approach.

The number of threads being used has increased causing changes in the floating point behavior.  In the past the smaller number of thread was accounted for in the tolerances used.

We have been using floating point (as compared to double) to increase throughput.  This has caused the rounding behavior to change even more and combined with the number of threads makes it worse.  This has also been made worse as we move to using SIMD processing like GPU and/or AVX instructions sets.

We have been enhancing the algorithms used to recover more of the pixels which would have been marked as invalid in the past are not valid.  This combined with 1 and 2 above is resulting in some pixels being included on some machine and not on others.  Since these are on the edge of useability these difference are handled by the algorithms with use this image and are not of concern for the system as a whole, but are causing problems with unit testing the algorithms.

We have also recently ran into the problem that two numbers (internal to the calculation) are the same and because of the rounding behavior one or the other is picked resulting in different outputs.  .  Again this is not a problem of the system as a whole, only with unit testing to flag for differences.

As a minor side example, we also have other non-linear algorithms with due to rounding behavior can give different outputs.  Since these algorithms are self correcting the final solution is good, but has a higher variability than easily accounted for unless the tolerances are opened larger than desired.

So, my questions is how to account for these issue in unit testing.

I strongly need unit testing because we have a team of programmers working on the system and we need the ability to detect when someone makes a change which unknowingly impacts other algorithms.  Yes this has happened in the past and the method being used at the time caught the change before it reached the final product.  As the primary algorithm developer I can use your help.  I have had many ideas, but they don’t work for all cases and it’s not clear when to use one of the different methods.

Edit: I now that this is frequently called regression testing but I also know that many time it is also generically called unit testing by many people, even if it's not completely correct.

I am not necessarily looking for a magic bullet (that would be nice) but I do need a way of handling these issues in a way which can be handled by others in the group which may not be as knowledgeable on the details.  If that is a “pick” one of these methods that is fine if it the rule are clear.  We do adjust the parameters when we change the algorithms, but once it is fixed the floating point behavior is still causing differences.  When we see differences we always investigate why and in general we try to adjust the algorithm to reduce the difference, but there are times where these is not possible because of the additional computation time.  If we stayed away from the limits this would not be an issue (as in the past) but to advance the technology we need to push the limits giving rise to the issues described.

You can see this in a simple example. Calculating an average of many numbers.  If you stay with number which are close to each other, there are simple methods to make sure the results are accurate.  Now when you allow for numbers which have large (orders of mag) difference, with threading, float compared to double, etc you can get very different results. Yes I know there are algorithms which can be used to fix these issue but they can be very computation expensive. While averaging is not my problem you could imagine that the difference don’t impact downstream processing but you still want to write a test to monitor the calculation.


答:
Apart from talking to people about it (question suggests you don't have colleagues on the project), I often find it a good approach to focus on the things I can do.

Usually there is some part of the code that I know I must write anyhow. The stuff I don't know how to write yet, is then replaced by stubs that either return dummy results, or use an approximation that is good enough to test the rest.

This keeps you productive. And by the time you need to implement the missing piece, you have the interface. And you have written a lot of code surrounding the problem, in the same problem domain, which usually helps me to generate ideas: you know more exactly what you are required to output, and what other inputs are available if it helps to solve the problem. Also, often the conclusion is that the missing piece does not need to be as all-encompassing as initially thought.


答: I usually put all db specific code (queries) in DAO's and transaction handling and business logic in services. This allows for service methods to invoke methods across multiple dao's and keep it all within same transaction. In my opinion, this is allows for better code reuse across dao's.</p>

ContentLicense: CC BY-SA 4.0

Title: Service layer vs DAO -- Why both?

Body:
I have been working with SpringMVC, Hibernate, and some databases in a java web application example.

There are a few different ones that do this, but this Spring 3 and hibernate integration tutorial with example has a model class, view (in jsp), and a service and dao classes for the controller.

My question is, don't both the service and DAO classes do the same thing? Why would you need them both?

This was the tutorial I was actually using: http://fruzenshtein.com/spring-mvc-security-mysql-hibernate/


问:
Design for a template class
I have an abstract class abstract class MathFunc that is used to implement the mathematical functions Rastrigin, Griewangk and Rosenbrock in their specific classes final class Rastrigin extends MathFunc,  final class Griewangk extends MathFunc and final class Rosenbrock extends MatjFunc.

This hierarchy of classes and how they are defined so far works flawlessly so I think there is no need to look for improvements on this area.

Now I have to implement another class Generation that will have some ArrayLists in it but the thing is I need to have a Generation implementation for each mathematical function described above.

So that I need something like:

```<code>ArrayList<Rastrigin> rast = new ArrayList<>();
ArrayList<Griewangk> grie = new ArrayList<>();
ArrayList<Rosenbrock> rose = new ArrayList<>();
</code>```

Inside these lists I have some Rastrigin/Griewangk/Rosenbrock objects that I need to instantiate.

I know from the past projects in C++ that I can use templates to specify a generic data type and I'm thinking that this is my solution. My implementation so far looks like this:

```<code>public class Generation <MathFunc> {
    private final ArrayList<MathFunc> pop = new ArrayList<>();
    private final ArrayList<MathFunc> nextpop = new ArrayList<>();
    private final ArrayList<MathFunc> Crossover = new ArrayList<>();

    Generation(MathFunc tp)
    {
        for(int i = 0; i < PopSize; i++)
        {
            pop.add(tp);
        }
    }
}
</code>```

But the problem is: can I use the abstract class to instantiate the objects that rely on it? Is there another way to do it? I'm quite confused about the usage of templates.

But doing Generation(Mathfunc tp) seems a little weird to me since abstract classes are not instantiable.

答:
You don't need to instantiate the Mathfunc class.  Instead, what you can do is to instantiate one of MathFunc's sub classes and treat the object as an instance of Mathfun.  For example:

```<code>MathFunc math = new Rastrigin();
Generation g = new Generation(math);
</code>```

Title: Design for a template class

Body:
You don't need to instantiate the Mathfunc class.  Instead, what you can do is to instantiate one of MathFunc's sub classes and treat the object as an instance of Mathfun.  For example:

MathFunc math = new Rastrigin();
Generation g = new Generation(math);


答:
First of all, it is not very clear if you compare floating point
numbers with exact values in your unit tests.  If you do so, this is
wrong and you should rely on approximate comparison of floating point
numbers [1].

That being said, if your computations are sensitive to factors such as
the number of threads involved, the precision of numbers used and the
other things you describe, then you should question the stability of
your numerical procedures.  If you are lucky, you can rewrite some
calculations to improve the stability without significantly change the
number of operations required.  But it might also happen, that writing
better procedures involves more calculations, so that you will have to
find an acceptable trade-off between time and precision.

[1] For instance, you can start here: http://www.gnu.org/software/gsl/manual/html_node/Approximate-Comparison-of-Floating-Point-Numbers.html


答:
To answer a bit of what you are asking: you can use the abstract as the declaring type, the type of your reference, but the (real) object should be that of a concrete/implementing type. Probably you already got that; indeed, in this case, probably using interfaces would be a plus.

To help some more, a nice tutorial on the template method is here: http://www.oodesign.com/template-method-pattern.html. Also, please read a bit about Java generics usage: http://docs.oracle.com/javase/tutorial/java/generics/types.html.

Title: Design for a template class

Body:
I have an abstract class abstract class MathFunc that is used to implement the mathematical functions Rastrigin, Griewangk and Rosenbrock in their specific classes final class Rastrigin extends MathFunc,  final class Griewangk extends MathFunc and final class Rosenbrock extends MatjFunc.

This hierarchy of classes and how they are defined so far works flawlessly so I think there is no need to look for improvements on this area.

Now I have to implement another class Generation that will have some ArrayLists in it but the thing is I need to have a Generation implementation for each mathematical function described above.

So that I need something like:

```<code>ArrayList<Rastrigin> rast = new ArrayList<>();
ArrayList<Griewangk> grie = new ArrayList<>();
ArrayList<Rosenbrock> rose = new ArrayList<>();
</code>```

Inside these lists I have some Rastrigin/Griewangk/Rosenbrock objects that I need to instantiate.

I know from the past projects in C++ that I can use templates to specify a generic data type and I'm thinking that this is my solution. My implementation so far looks like this:

```<code>public class Generation <MathFunc> {
    private final ArrayList<MathFunc> pop = new ArrayList<>();
    private final ArrayList<MathFunc> nextpop = new ArrayList<>();
    private final ArrayList<MathFunc> Crossover = new ArrayList<>();

    Generation(MathFunc tp)
    {
        for(int i = 0; i < PopSize; i++)
        {
            pop.add(tp);
        }
    }
}
</code>```

But the problem is: can I use the abstract class to instantiate the objects that rely on it? Is there another way to do it? I'm quite confused about the usage of templates.

But doing Generation(Mathfunc tp) seems a little weird to me since abstract classes are not instantiable.


问:
Use MAC address for license
One of my company product need to implement a license mechanism. I'm planing to generate a key  base on users PC MAC address. But I'm bit scared is this method confuse with some advance hardware. configurations such as.

Multiple network cards.

Virtualization.

Mac address change possibilities(?)

Working with VPNs.

Is it a good idea to generate license key with MAC address? Some ideas?

答:
Implementing a license mechanism has always been bit of challenge to developers.But if you use MAC address, IMO virtualization & Multiple N/w cards would pose challenge.

There are other options which can be considered. (tht i'm aware)

Based on Hardware ID's (Replacing Hware is also a challenge)

Other License Development kits (CryptoLicensing && SafeNetSolutions && MS-SLPservices and so many..)

Based on Hardware Devices (Dongle & SD cards etc)

Obviously none of the above options are hack-proof. Considering product & Company needs evaluate them carefully.

Don't spend too much time in complicating it, do think of those loyal customers (money paying).

Title: Use MAC address for license


问:
Is there any sorting algorithm which is not inherently sequential and is task distributable?
After googling for a couple hours, I came to a conclusion that all sorting algorithms are inherently sequential which can be data distributed but not task distributable.

Is there any algorithm which is not inherently sequential and is task distributable?

答:
You overlooked sleep-sort which is task distributed. Here is an implementation for the Bourne shell:

```<code>input="10 4 5 1"
for n in $input; do
  (sleep $n; echo $n) &
done
</code>```

When the program completes, the sorted list of numbers is printed on the standard output.  (Note that you could need to add job management to determine when the subprocesses finish.)

Body:
You overlooked sleep-sort which is task distributed. Here is an implementation for the Bourne shell:

input="10 4 5 1"
for n in $input; do
  (sleep $n; echo $n) &
done

When the program completes, the sorted list of numbers is printed on the standard output.  (Note that you could need to add job management to determine when the subprocesses finish.)


问:
What to do with bugs that do not repro?
I have a tester that while testing will have an error occur (ok so far), but then he frequently reports it right away.  We (the developers) then later find that the tester has not tried to reproduce the issue and (when asked) cannot find a way to make it happen again.

Now these are still bugs, I don't want to ignore them.  But without repro steps I am kind of stuck.  Sometimes there is a stack trace (though frequently it is not useful because this is compact framework and there are no line numbers).  But when there is one I can take the stack trace and crack open the code and start guessing, but that does not lead to testable "fixes".

What do you do in scenarios like this?

答:
There are two sorts of bug that are not reproducible:

1) Those that a tester (or user) has seen once but has either not been able to or not attempted to reproduce.

In these situations you should:

Very briefly check the basic course of actions which showed the defect to ensure that it's not reproducible.

Speak to the tester / user to see if there is any other information which may help.

Cross reference them with any other defects that might be related to see if you have enough information to look into them based on multiple instances.  You may find that this one issue does not give you enough information to go on however when coupled with a number of other issues it may suggest to you something not right that is worth investigating.

If you still don't have enough to go on then you need to explain to the user / tester that you don't have enough information.  Outline to them politely what enough information would look like and why it's needed.

2) Those where they can not be reliably reproduced, however there is enough evidence (in terms of repeated occurrences) to suggest that the defect does exist, then I tend to see that these are developer issues and that the developer - supported by the tester / user - needs to investigate.

This is likely to be slow and painful, you're likely going to have to walk the code, add more logging, look at the data and speak to the testers / users in depth but if there is enough evidence to suggest that it's likely there is an issue you do need to take ownership of it and do whatever needs to be done to fix it.

ContentLicense: CC BY-SA 2.5

Title: What to do with bugs that do not repro?


答:
Algorithms that are based on trial and error should fit your description, as the trials can be done in parallel.

Examples would be:

Bogosort, which shuffles the data until it's sorted

StackSort, which looks for sort algorithms on stackoverflow, running them one by one until a correct answer is returned

Title: Is there any sorting algorithm which is not inherently sequential and is task distributable?

Body:
After googling for a couple hours, I came to a conclusion that all sorting algorithms are inherently sequential which can be data distributed but not task distributable.

Is there any algorithm which is not inherently sequential and is task distributable?


问:
Is there a downside to using Access as a database?
I have inherited an application that stores data in multiple tables in Microsoft Access; the Access DB is only used for storage, all data processing is handled by the app (VB.net).

Is this good practice? I need to build a similar app from scratch and am unsure of what is 'normal' practice.

I have tried Googling the question in various formats and checked through numerous results (including many on this forum) but all questions seem to relate to where you are programming within Access rather than simply using it for data storage.

I guess I could be more specific and say would SQL Server Express or similar be a better option and if so why?

If you are reading this post due to having a similar question then check out this link provided by @DanielB below - https://stackoverflow.com/questions/694921/ms-access-mdb-concurrency

答:
MSAccess databases aren't typically used for a couple reasons. In the past, they were flaky and didn't accept multiple connections at once.  When the MSAccess database is being used, a lock file is created (ldb).  When that lock file is present, no one else can access the database.  I found that when there was a single use application, MSAccess's performance would severely degrade after about 50k rows.  This is probably better now, but it certainly wasn't tuned for larger uses.

What is more typical is to use a more robust database system like postgres, mysql, or MSSQL.  For single connection databases, I've used Derby (with Java).

As far as VB goes, you won't find professional solutions using VB as client software to a database.  Well, perhaps there are some solutions being sold, but personally, I would avoid them.

Typically, your processing will be done in a language like C#, C++, Java, Perl, Python, or other popular languages.  Libraries will be used to connect to the database that are separate from the language.  Some solutions will use SQL to query and receive data, and other solutions will use a Persistence library to create objects from the data (this is becoming more common).

As far as best practice goes, I've always found it best to be consistent.  If you have a shop of four people that understand MSAccess and VisualBasic, then it makes a lot of sense to continue doing it this way.  If there is a goal in the company to move away from it due to failures in the past, you can keep using VB and switch to another database.  Look into Linking Tables in MSAccess - I used a VB application on an MSSQL database by linking the MSSQL tables into an MSAccess database.  The VB didn't know the difference between a naitive MSAccess table, and a linked table located on another server.  The VB solution was still flaky, but worked much better with larger datasets.

Hope this helps!


问:
Tips for developing a mobile app with a team
I am currently a high school student, I've been assigned to manage a group in my school to develop a mobile app and the problem is that all of us have no experience in making a project in a team and the greater problem is that we have only till the end of the month to submit the app.

Can I have some tips to overcome these problem?

Also we decided to do the app in Python with Kivy, we know Python.

答: I did some research on this a year and a half ago, so this info might be a little stale.  The way to go seemed to be to make an HTML5 application.  What this gets you is this:  It'll run on Android, iPhones, and any other phone with an HTML5 compliant browser.  If you were to focus on Android, you'd be writing in Java.  iPhone, Objective C.  It's out of your realm in either case, but HTML5 should be fairly straight-forward in comparison.</p>


答:
Sit down together and make a planning.

Have 1 meeting (not more) on a regular base (every week) all together to be always updated on the status.

Split the application in different subtask and assign a task to everyone. If everyone starts putting hands everywhere it will be a mess.

Decide incremental "deliverables": Example: "by day x part y should be completed"

Review the code -> I write something, you review my code and the opposite

Decide upfront how to interface the different components among each other (This is very important in python since you don't have a compiler check for this like in Java...)

Don't put the target to high! Do something easy!

Title: Tips for developing a mobile app with a team

Body:
I am currently a high school student, I've been assigned to manage a group in my school to develop a mobile app and the problem is that all of us have no experience in making a project in a team and the greater problem is that we have only till the end of the month to submit the app.

Can I have some tips to overcome these problem?

Also we decided to do the app in Python with Kivy, we know Python.


问:
MVC to create desktop and mobile webapps?
I'm planning the creation of a webapp with a dedicated mobile web interface and a dedicated desktop/tablet interface.

I am considering ASP.NET MVC, but it is clear to me that MVC is for separation of concerns as explained here, anyway in my case i'd like to minimize the code and to support elegantly phones and desktop (may be landscape tablet can be "desktop" too).

So is MVC a wise choice in this case or which is the 1st stop for this kind of xdevice web app?

答:
A pattern is very useful until it's not a constraint.
Split your application in different components, decide how to connect them before and then program them.
If you fully decouple the control part to the UI then is very easy to reuse the code for both the web application and the desktop application.
In the end you have to deal with 3 components:

The UI (web interface or GUI)

The control part (which is the part that does the data crunching)

The "storage" part (on file or database, depends from your application)

Is this MVC? I don't know but it's probably what you are going to do.

Patterns are guidelines, not boundaries! ;)


问:
How can I write complex validation and business logic that can be reused in both direct data model changes and pending dialog changes?
I was hoping for some advice:

I need to design a software solution for a medium-sized java / Swing application.

The application will have about 200 use cases requiring complex data validation and business logic.

Typically, this is my usual design:

Create a simple POJO for each use case, with a custom constructor and custom validation and business logic within it's execute method. These Operations implment simple and complex data validation such as required fields, unique names and more complex constraints.

Create a single controller that has a method for every use case. Each method takes custom parameters, constructs and executes it's related operation.

For the sake of simplicity, I won't mention details about Data Model notification or Operation queuing mechanism.

This solution has worked will in the past because it encourages all developers to reuse existing controller methods and validation, however:

The new application will use dialogs extensively for data entry;

These dialogs are expected to implement the same complex data validation and business logic that the controller implements, however the dialogs are not expected to update the data model until the OK button is clicked.

I hate the idea of writing multiple versions of the same complex validation and business logic, due to the maintenance nightmare it invites.

How can I perform complex business logic and validation for both standard data model changes and "pending" dialog changes, given that the dialog doesn't commit it's changes until the OK button is clicked?

The data model may be quite large, so creating an in-memory clone of it and the controller doesn't seem viable.

Does anyone have any suggestions? If so, I'll be forever in your debt.

答:
I refrain from including validation in my data model objects. I make them very simple POJOs that don't have any knowledge about the content of the values, business logic that drives them, and the state of the application.

I've create verification classes that are separate from both the controller and the data model.  These are used during the import of data, and the UI that does conditional highlighting based on the validity of inputs.  I make the background of a cell table light-red when the data in it doesn't match expected inputs.  It's a simple matter of having a series of classes that are capable of verifying different inputs, and then, on construction, associating them with the proper input fields / cells.  They're very straight forward, and dead simple to use during a data import.  Mind you, during data import, I only log errors in expected data, and then allow the user to modify the incorrect data.  I could easily have chosen to reject the import altogether.

Hope this helps.


答:
I always try and look at it from an end user perspective. Its very easy to think of a "cool" idea as a developer that you can spend ages working on that actually adds very little to your app.

Ideally you want to map out all the features in your app and prioritize them according to the benefit to the end user, personally I use MOSCoW, although as long as you keep your method of prioritization the same throughout it can be as simple as a 1 - 5.

After which if you still find that this feature is an essential part of your app then as people have already said, ask! I don't think i've ever encountered a problem that eventually hasn't been solved either by a colleague or those nice people over on Stackoverflow.


问:
How should we "pick the comfortable programming language" in an interview?
When they ask you to choose the programming language you are comfortable with before an interview, is it to ask questions about the programming language or to check how well you code in it?

Like for example, if I don't know what iterators are in Python but I'm comfortable with Python because of its in-built facilities, should I use Python or not?

I might have studied everything about Haskell for ages but it takes me longer to write code in Haskell (imagine writing an AVL tree in Haskell). Is Haskell a good choice then?

答:
is it to ask questions about the programming language or to check how well you code in it?

Neither. It is to put you at ease, using a language you know.

The interviewer is looking at how you approach problems and doesn't care about what language is being used. How you solve problems and approach problem solving is what is being looked at, which is why they say - "choose the programming language you are comfortable with".

Now, if the interviewer can see that one is not competent in the chosen language, that can ring alarm bells (the thinking would be "this is the language this person says they are comfortable with, but they can't get even simple, common syntax right. Oh uh").

You should choose a language that you know how to write - not something you need to have a reference to work with. A language you use on a daily basis is best.

A language that you can code at while talking about the solution is what you want to use.

It is not normally expected that the code written will compile ;)


答:
It really depends on the position you're going for, i'd perhaps be tempted to try and find out what the format of the interview was beforehand, i found usually if they are going to ask you to code something they'll at least give you an outline.

If you going through an agent get them to do some digging for you, remember they get a nice bonus for getting you the job so make them work for their money!

In terms of picking the language i'd pick the one you can code in the quickest and cleanest with the minimum of googling/reference material.

Lastly, relax! Remember you're getting an interview because they want you to be the right person, unless your applying for a very senior role they won't expect you to be an programming encyclopedia.

Title: How should we "pick the comfortable programming language" in an interview?

Body:
When they ask you to choose the programming language you are comfortable with before an interview, is it to ask questions about the programming language or to check how well you code in it?

Like for example, if I don't know what iterators are in Python but I'm comfortable with Python because of its in-built facilities, should I use Python or not?

I might have studied everything about Haskell for ages but it takes me longer to write code in Haskell (imagine writing an AVL tree in Haskell). Is Haskell a good choice then?


答:
Personally if you're able to move away from access do it, I've had clients who have really suffered because they simply couldn't or wouldn't "bite the bullet".

As Kieveli mentioned Access databases are horrible when it comes to storing large amounts of data, remember applications should always be designed with the benefit to the end user in mind. Imagine you've got an office full of people who have a horribly slow system wasting hours of their time every single week?

Speaking from personal experience moving an access database to SQL Server really isn't that painful providing you plan properly, the question is do you have the technical skills in house to move to something like vb.net etc.

Title: Is there a downside to using Access as a database?

Body:
I have inherited an application that stores data in multiple tables in Microsoft Access; the Access DB is only used for storage, all data processing is handled by the app (VB.net).

Is this good practice? I need to build a similar app from scratch and am unsure of what is 'normal' practice.

I have tried Googling the question in various formats and checked through numerous results (including many on this forum) but all questions seem to relate to where you are programming within Access rather than simply using it for data storage.

I guess I could be more specific and say would SQL Server Express or similar be a better option and if so why?

If you are reading this post due to having a similar question then check out this link provided by @DanielB below - https://stackoverflow.com/questions/694921/ms-access-mdb-concurrency


答:
If you had more time i'd say do some research on agile/scrum but heres a cut down version:

1)  Initially you want to sit down together and very carefully plan out your application and all of its features. You also want to sketch out(wireframe) the user interfaces remember that their are a huge variety screen sizes, try and keep them minimalist.

Remember features are for the benefit of the end user, always remember if someone wants to add something, ask what the benefit is!

2) You absolutely should have more than one meeting a week, you should be meeting every day even if for only 15 minutes either face to face or on skype. The reason being you can discuss problems, find solutions together and most importantly adjust timescales and resources accordingly

3) You should then assign priority to each of these features along with the amount of time it will take you as a team, we use the MoSCoW scale for prioritization. You should then see if your specification can be feasibly finished in the time required, if it doesn't you may need to either redesign some features or drop low priority ones.

4) Start working as a team on the high priority items working your way down the list.

5) As you complete each item you need to go back to you original specification and check you've actually achieved the goal.

I can't stress enough how important you're daily conversations are, don't ever let anyone not attend unless they are on their death bed! If you're going to manage the project you need to know about issues very quickly.


答: I managed to solve the problem as stated here. It looks like factory pattern would work best in this scenario.</p>

Title: Design for a template class


问:
Usage of magic strings/numbers
This is somewhat controversial topic, and I guess there is as many opinions as there are programmers. But for the sake of it, I want to know what are the common practices in business (or in your work places).

In my work place we have a strict coding guidelines. One section of that is dedicated to magic strings/numbers. It states (for C#):

Do not use literal values, either numeric or strings, in your code other than to define symbolic constants. Use
  the following pattern to define constants:

```<code>public class Whatever
{
   public static readonly Color PapayaWhip = new Color(0xFFEFD5);
   public const int MaxNumberOfWheels = 18;
}
</code>```

There are exceptions: the values 0, 1 and null can nearly always be used safely. Very often the values 2 and
-1 are OK as well. Strings intended for logging or tracing are exempt from this rule. Literals are allowed
when their meaning is clear from the context, and not subject to future changes.

```<code>mean = (a + b) / 2; // okay
WaitMilliseconds(waitTimeInSeconds * 1000); // clear enough
</code>```

An ideal situation would be some official research paper showing effects on readability/maintainability of the code when:

Magic numbers/strings are all over the place

Magic strings/numbers are replaced by constant declarations reasonably (or in different degrees of coverage) - and please don't shout at me for using "reasonably", I know everyone has different idea what "reasonably" is

Magic strings/numbers arereplaced in excess and in places where they wouldn't have to be (see my example below)

I would like to do this to have some scientificaly-based arguments when arguing with one of my collegues, who is going to the point of declaring constants like:

```<code>private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;
</code>```

Another example would be (and this one is in JavaScript):

```<code>var someNumericDisplay = new NumericDisplay("#Div_ID_Here");
</code>```

Do you stick DOM IDs on top of your javascript file if that ID is used only in 1 place?

I have read the following topics:

StackExchange

StackOverflow

Bytes IT Community

There is many more articles, and after reading these some patterns emerge.

So my question is should be using magic strings and numbers in our code?  I am specifically looking for expert answers that are backed by references if possible.

答:
There shouldn't be anything controversial about it. The point is not about wether to use magic numbers or not, the point is to have readable code.

Consider the difference between: if(request.StatusCode == 1) and if(request.HasSucceeded). In this case, I would argue the latter is far more readable, but that doesn't mean you can't ever have code like int MaxNumberOfWheels = 18.

P.S.: This is why I absolutely hate coding guidelines. Developers should be mature enough to be capable of making judgement calls like this; they shouldn't leave it to a piece of text formed by god knows who.

Title: Usage of magic strings/numbers


答:
Defining semicolon as a constant is redundant, because semicolon is already constant by itself. It is not going to ever change.

It's not like one day somebody will announce "change of terminology, + is the new semicolon now", and your colleague will happily rush just to update the constant (they laughed at me - look at them now).

There's also a matter of consistency. I guarantee that his NumberTen constant will NOT be used by everyone (most coders are not out of their mind), so it won't serve whatever purpose it was expected to anyway. When the apocalypse comes and "ten" gets globally rescaled to 9, updating the constant will NOT do the trick, because it will still leave you with a heap of literal 10s in your code, so now the system becomes totally unpredictable even within the scope of a revolutionary assumption that "ten" means "9".

Storing all settings as consts is something I'd have second thoughts about, too. One should not do this lightly.

What examples of this type of use have we gathered so  far? Line terminator... max retry count... max number of wheels... are we positive these will never change?

The cost is that changing default settings requires recompiling an application, and in some cases, even its dependencies (as numeric const values may get hard-coded during compilation).

There's also the testing and mocking aspect. You defined the connection string as a const, but now oops you can't mock database access (establish a fake connection) in your unit test.

Title: Usage of magic strings/numbers

Body:
This is somewhat controversial topic, and I guess there is as many opinions as there are programmers. But for the sake of it, I want to know what are the common practices in business (or in your work places).

In my work place we have a strict coding guidelines. One section of that is dedicated to magic strings/numbers. It states (for C#):

Do not use literal values, either numeric or strings, in your code other than to define symbolic constants. Use
  the following pattern to define constants:

```<code>public class Whatever
{
   public static readonly Color PapayaWhip = new Color(0xFFEFD5);
   public const int MaxNumberOfWheels = 18;
}
</code>```

There are exceptions: the values 0, 1 and null can nearly always be used safely. Very often the values 2 and
-1 are OK as well. Strings intended for logging or tracing are exempt from this rule. Literals are allowed
when their meaning is clear from the context, and not subject to future changes.

```<code>mean = (a + b) / 2; // okay
WaitMilliseconds(waitTimeInSeconds * 1000); // clear enough
</code>```

An ideal situation would be some official research paper showing effects on readability/maintainability of the code when:

Magic numbers/strings are all over the place

Magic strings/numbers are replaced by constant declarations reasonably (or in different degrees of coverage) - and please don't shout at me for using "reasonably", I know everyone has different idea what "reasonably" is

Magic strings/numbers arereplaced in excess and in places where they wouldn't have to be (see my example below)

I would like to do this to have some scientificaly-based arguments when arguing with one of my collegues, who is going to the point of declaring constants like:

```<code>private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;
</code>```

Another example would be (and this one is in JavaScript):

```<code>var someNumericDisplay = new NumericDisplay("#Div_ID_Here");
</code>```

Do you stick DOM IDs on top of your javascript file if that ID is used only in 1 place?

I have read the following topics:

StackExchange

StackOverflow

Bytes IT Community

There is many more articles, and after reading these some patterns emerge.

So my question is should be using magic strings and numbers in our code?  I am specifically looking for expert answers that are backed by references if possible.


答:
Adam Bien points out in his book the fact that the JPA EntityManager is a good universal implementation of the DAO:

http://realworldpatterns.com/

In the Java EE world there's almost never a need to write your own DAO because JPA implementations include one.  You only have to write the service layer.

Implementing your own DAO layer is really a hangover from the very poor J2EE architecture of 15 years ago, but many people still feel compelled to do it.  These custom DAO layers often provide nothing more than forwarding functions that call the corresponding method on EntityManager.

So to answer your question, yes you need a service layer and a DAO, but you only have to write the service layer.

Title: Service layer vs DAO -- Why both?


答:
I do QA on a large commercial code, this irritating scenario does come up way too often. Usually it is indicative of not having ironclad proceedures for building the binary on all the platforms we support. So if the developer builds his own code (which he has to do to debug and fix), and doesn't follow the same build proceedure to the letter, there is a chance that system dependent bugs will appear to magically vanish (or appear). Of course these things usually get closed with "works for me" in the bug database, and if they fail the next time that problem is run, the bug can be re-opened. Whenever I suspect a bug may be system dependent, I try to test it on a variety of platforms and report under which conditions it happens. Oftentimes a memory corruption issue onlt shows up if the corrupted data is of large enough magnitude to cause a crash. Some platforms (HW and OS combinations) may crash closer to the actual source of the corruption, and this can be very valuable for the poor guy that has to debug it.

The tester needs to do some value added, beyond just reporting that his system shows a failure. I spend a lot of time screening out false positives -maybe the platform in question was overloaded, or the network had a glitch. And yes sometimes you can get something that is truly affected by random timing events, hardware bugs can often be like proto example: If
two data requests come back a exactly the same clock period, and the hardware logic for handling the potential conflict is faulty, then the bug will only show up intermittently. Likewise with parallel processing, unless by careful design you've constrained the solution to be independent of which processor happened to be faster, you can get bugs that only happen once in a blue moon, and their statistical imporbablity makes debugging a nightmare.

Also our code is being updated, usually many times daily, tracking down an exact sourcecode revision number for when it went south can be very useful information for the debugging effort. The tester shouldn't be in an adversarial relationship with the debuggers and developers, he is there as part of a team to improve the quality of the product.

Title: What to do with bugs that do not repro?

Body:
I have a tester that while testing will have an error occur (ok so far), but then he frequently reports it right away.  We (the developers) then later find that the tester has not tried to reproduce the issue and (when asked) cannot find a way to make it happen again.

Now these are still bugs, I don't want to ignore them.  But without repro steps I am kind of stuck.  Sometimes there is a stack trace (though frequently it is not useful because this is compact framework and there are no line numbers).  But when there is one I can take the stack trace and crack open the code and start guessing, but that does not lead to testable "fixes".

What do you do in scenarios like this?


答:
I've had some experience regarding this issue in the past in a large corporation.

As user base grows, security and performance issues emerged because the Access files where the data resided had to be stored in a network shared folder, and all users had to have W/R access to it.

This is not theorethical, this is real-world experience, Access databases don't scale well to tens of simultaneous users, let alone a couple of hundreds geographically spread.

With free and good database systems like PostgreSQL available, there's little reason to go with Access except the following: lack of thechnical know how.


答:
... when arguing with one of my collegues, who is going to the point of
  declaring constants like:

```<code>private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;
</code>```

The argument you need to be making with your colleague isn't about naming a literal space as Space but his poor choice of name for his constants.

Let's say your code's job is to parse a stream of records which contain fields separated by semicolons (a;b;c) and are themselves separated by spaces (a;b;c d;e;f).  If whoever wrote your spec calls you up a month from now and says, "we were mistaken, the fields in the records are separated by pipe symbols (a|b|c d|e|f)," what do you do?

Under the value-as-name scheme your colleague prefers, you'd have to change the value of the literal (SemiColon = '|') and live with code that continues to use SemiColon for something that isn't really a semicolon anymore.  That will lead to negative comments in code reviews.  To abate that, you could change the name of the literal to PipeSymbol and go through and change every occurrence of SemiColon to PipeSymbol.  At that rate you might as well have just used a literal semicolon (';') in the first place, because you'll have to evaluate each use of it individually and you'll be making the same number of changes.

Identifiers for constants need to be descriptive of what the value does, not what the value is, and that's where your colleague has made a left turn into the weeds.  In the field-splitting application described above, the semicolon's purpose is a field separator, and the constants should be named accordingly:

```<code>private const char FieldSeparator = ';';    // Will become '|' a month from now
private const char RecordSeparator = ' ';
private const int MaxFieldsPerRecord = 10;
</code>```

This way, when the field separator changes, you change exactly one line of code, the declaration of the constant.  Someone looking at the change will see just that one line and will immediately understand that the field separator changed from a semicolon to a pipe symbol.  The remainder of the code, which didn't need to change because it was using a constant, remains the same, and the reader doesn't have to dig through it to see what else was done to it.

Title: Usage of magic strings/numbers

Body:
... when arguing with one of my collegues, who is going to the point of
  declaring constants like:

private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;

The argument you need to be making with your colleague isn't about naming a literal space as Space but his poor choice of name for his constants.

Let's say your code's job is to parse a stream of records which contain fields separated by semicolons (a;b;c) and are themselves separated by spaces (a;b;c d;e;f).  If whoever wrote your spec calls you up a month from now and says, "we were mistaken, the fields in the records are separated by pipe symbols (a|b|c d|e|f)," what do you do?

Under the value-as-name scheme your colleague prefers, you'd have to change the value of the literal (SemiColon = '|') and live with code that continues to use SemiColon for something that isn't really a semicolon anymore.  That will lead to negative comments in code reviews.  To abate that, you could change the name of the literal to PipeSymbol and go through and change every occurrence of SemiColon to PipeSymbol.  At that rate you might as well have just used a literal semicolon (';') in the first place, because you'll have to evaluate each use of it individually and you'll be making the same number of changes.

Identifiers for constants need to be descriptive of what the value does, not what the value is, and that's where your colleague has made a left turn into the weeds.  In the field-splitting application described above, the semicolon's purpose is a field separator, and the constants should be named accordingly:

private const char FieldSeparator = ';';    // Will become '|' a month from now
private const char RecordSeparator = ' ';
private const int MaxFieldsPerRecord = 10;

This way, when the field separator changes, you change exactly one line of code, the declaration of the constant.  Someone looking at the change will see just that one line and will immediately understand that the field separator changed from a semicolon to a pipe symbol.  The remainder of the code, which didn't need to change because it was using a constant, remains the same, and the reader doesn't have to dig through it to see what else was done to it.


答:
Jet-SQL is horribly documented. That alone is a reason for me to stay away from Access.

https://stackoverflow.com/questions/11265817/where-can-i-find-a-complete-reference-for-microsoft-access-sql

T-SQL (SQL Server) on the other hand is much more flexible and you can find tons of documentation, blogs and experts that can help you.

Of course Access is a desktop database while SQL Server is a full blown Client-Server database.

There are some other desktop databases out there (I have been using Advantage Database Server, but that's a niche product, too).


答:
Access databases don't scale well but they are easy to handle and distribute. If you are using an Object Relational Mapper (O/R-mapper) supporting different database types as an interface to your database, your application will be much less dependent on a specific database type. This allows you to start with Access and to move to another database later.

I did this once and started a project with Access and a C# front-end, because databases can be set up and developed very easily with Access. Later I moved to an Oracle database because my customer has an Oracle database. Only a few changes where required in my application.


问:
How to Deal With The "Automation is Easy" Mindset?
The title says it all. Some employees in our company believe that automated tests are "easy" and that it "should take a day" to write suites of COM and UI tests. What can be done to counter this? </p>

<p>Note: I'm not asking about how to promote automation. That isn't the problem. Automated testing and processes are being promoted and requested all the time here. The issue is that some individuals don't understand that automation is not "easy" nor is it "fast". </p>

答:
Testing in general is not easy, and nor should it be. If Boeing or Mercedes didn't test their products as rigorously as they do then they would either be bankrupt due to law-suits or go out of business for selling such poor quality items. Would you drive a car at 70 miles an hour knowing that the steering wheel may or may not fall to pieces?

It's very hard to suggest ways to cope with the mindset without understanding who those people are, or their reasons. Most managers and directors think of costs and are judged by what is produced. Using this criteria makes it very difficult for them to justify spending time on tests. If this is the case with you then you will need to find ways to present this task as being beneficial in the long run, which of course it is.

Just because software isn't tangible doesn't mean that we can get away without thinking about the implications of the systems we build not working. I bet Amazon have automated tests and I bet there are people there who know only too well the cost implications of their websites/services failing.


问:
Product backlog acceptance criteria
I read on a similar forum https://stackoverflow.com/questions/8117530/examples-for-acceptance-criteria-for-a-user-story about putting in the acceptance criteria for product backlog item.

I am working on a Scrum based project and I need more info as my backlog item is as follows -

UserProfiles ( I am using this in the title field in tfs 2013) and the description contains all the "As a user I want to be able to create new users and assign permissions'

The acceptance criteria talks about how the user interacts with the UI (as discussed in one of the answers in the above link - which is very logical)

For example

As the user clicks on the home button, system will bring up 3 options

And then the user can enter their user name

Is this the right approach I am using to use title for PBI and put the actual user story in description field in tfs

Thanks in advance

答:
yes this is a right approach and you can add additional information e.g. like performance parameters, usability etc.

basically it should be clear to developers what you will use to accept the work they are doing. If you are not developer yourself or you don't know the co debase then it should be helpful if you can use some of your developers time for backlog grooming to understand what  major assumptions they will make when they pick the PBI in the next iteration. and then just make those assumption part of acceptance criteria e.g. we will only support English letters etc..

Title: Product backlog acceptance criteria


答:
```<code>private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;
</code>```

So your colleague is aiming for a Daily WTF entry.  Those definitions are silly and redundant.  However, as has been pointed out by others, the following definitions would not be silly or redundant:

```<code>private const char StatementTerminator = ';';
private const char Delimiter = ' ';
private const int  BalanceInquiryCode = 10;
</code>```

"Magic" numbers and strings are constants that have meaning beyond their immediate, literal value.  If the constant 10 has meaning beyond "ten things" (say as a code for a specific operation or error condition), that's when it becomes "magic" and should be replaced by a symbolic constant that describes that abstract meaning.

Beyond clearly describing intent, symbolic constants also save you some headaches when you misspell a literal.  A simple transposition from "CVS" to "CSV" in one line of code got all the way through unit testing and QA and made it into production, where it caused a particular operation to fail.  Yes, obviously the unit and QA tests were incomplete and that's it's own problem, but using a symbolic constant would have avoided that bit of heartburn altogether.

Title: Usage of magic strings/numbers

Body:
private const char SemiColon = ';';
private const char Space = ' ';
private const int NumberTen = 10;

So your colleague is aiming for a Daily WTF entry.  Those definitions are silly and redundant.  However, as has been pointed out by others, the following definitions would not be silly or redundant:

private const char StatementTerminator = ';';
private const char Delimiter = ' ';
private const int  BalanceInquiryCode = 10;

"Magic" numbers and strings are constants that have meaning beyond their immediate, literal value.  If the constant 10 has meaning beyond "ten things" (say as a code for a specific operation or error condition), that's when it becomes "magic" and should be replaced by a symbolic constant that describes that abstract meaning.

Beyond clearly describing intent, symbolic constants also save you some headaches when you misspell a literal.  A simple transposition from "CVS" to "CSV" in one line of code got all the way through unit testing and QA and made it into production, where it caused a particular operation to fail.  Yes, obviously the unit and QA tests were incomplete and that's it's own problem, but using a symbolic constant would have avoided that bit of heartburn altogether.


问:
How do I approach a serious F# project without C# knowledge?
So, essentially the project I wish to undertake is an SVG editor. I would prefer to use WPF because then I can leverage XAML for my application layout (that designer is so nifty). Unfortunately, I have only been using the .NET framework for just a few months, and am still unfamiliar with most of the class names.

The goal was to use F# because it is a functional programming language and F#'s recursion and wonderful list operations combined with tuples will work well for what I am trying to achieve. And the goal is to use .NET because of its huge library of available and documented classes with examples.

I have already looked at this question. https://softwareengineering.stackexchange.com/questions/3129/is-there-a-canonical-book-on-f  But the answers are just for F# in general and assume you already know C# , which is not particularly useful for me.

The top book as an answer for the question referenced above was Real-World Functional Programming: With Examples in F# and C#. However, the 3 star amazon review on this book while quite harsh and perhaps exaggerated correctly illustrates my problem.

If you're interested in functional programming, but you're not a C# looking to learn F#, you can safely skip this book.

I have looked on online for WPF F# examples,  there are various code snippets here and there, but nothing substantial or demonstrating it being used outside a single file script .fsx, and nothing really enterprise-level or even at least professional grade.

So even Microsoft doesn't really have a lot of examples on how to do .NET stuff in F#. The examples I have found are usually only features unique to F#. Take a look at F# 's basic and advanced sections, and you'll find they are guilty of only teaching syntax.
For example, the MSDN on WPF for the Line class does not have any code examples in F#.

When you scroll down the the code sample tab for F# it just says

```<code>No code example is currently available or this language may not be supported.
</code>```

With so few available code examples, I am finding it hard to undertake this project.

My question

I would appreciate help with understanding how I should approach this project using F# when I don't know C# all that well.

答:
Break the problem into two parts.

Learn the basics of F# by excluding the use of WPF. Learn how to write functions without using mutables and while statements and using function composition. Once you have this done learn how to make use of mutables to update state.

Learn how to use WPF in F# by reading Learning WPF through F#, and vice versa, by John Liao.

If you can't find any code you like in F#, remember that F# is a descendent of OCaml so Google for OCaml and SVG, and you might find something of interest. While F# can't compile OCaml, it is very close and should not take much time to convert. I converted a large amount of OCaml to F# and all of it converted.


问:
Aggregate Boundary repository/service design
I am trying to apply DDD to the design of a Release Management system.

Domain Entities

Project: The project/product/system.

ProjectEnvironment: The environments (Test, Staging, Prod) that exist for this project.  Each project has its own defined environments.

ProjectVersion: A specific version of the project. This would be associated with a deployment package.

Aggregate Boundary

From this I would have Project be the aggregate root and ProjectEnvironment and ProjectVersion be aggregates of Project.  Neither of these can exist without Project.

Repository

I would then only have a ProjectRepository which would provide persisted Projects with all the included ProjectVersion and ProjectEnvironment aggregates (and consequently can only be accessed through their respective Project).

Questions

Should there be a VersionRepository and a EnvironmentRepository?  A GetVersionById() method on the ProductRepository sounds wrong.  But then wouldn't supplying multiple repositories threaten the aggregate boundary?

Should there be a 'ProjectService' which would handle and validate the aggregates using the three repositories?  In order to safeguard against invalid data, client code would only be able to reference the 'ProjectService'.

答:
If your ProjectVersion does not make sense without a Project then there's no need to have a repository of them. All versions for a project should be contained wtihin the aggregate. Furthermore your aggregate itself is where your validation should take place. This ensures that your aggregate is always consistent and valid.

```<code>public class Project {
    private List<ProjectVersion> Versions = new List<ProjectVersion>();

    public void AddVersion(Version version, string notes) {
        if(Versions.Any(x => x.Version > version)) {
            throw new Exception("Invalid version given. Version cannot be lower than the highest current version.");
        }
        Versions.Add(new ProjectVersion(this, version, notes));
    }
}
</code>```

Body:
If your ProjectVersion does not make sense without a Project then there's no need to have a repository of them. All versions for a project should be contained wtihin the aggregate. Furthermore your aggregate itself is where your validation should take place. This ensures that your aggregate is always consistent and valid.

public class Project {
    private List<ProjectVersion> Versions = new List<ProjectVersion>();

    public void AddVersion(Version version, string notes) {
        if(Versions.Any(x => x.Version > version)) {
            throw new Exception("Invalid version given. Version cannot be lower than the highest current version.");
        }
        Versions.Add(new ProjectVersion(this, version, notes));
    }
}


答:
Software is the business of automating things.

We write software to make boring, repetitive, and labor intensive tasks easier for us.  We write software to automate making reports, gathering data, communicating with others, etc.  Writing automated tests is really just writing software to make sure our other software works the way we expect it to.

If your coworkers understand that writing software is hard and takes time, it should be fairly easy to show them that writing more software should be hard and take time.  It would be nice to get all the benefits of automation for free, but, as always, we need to put the work in up front to get the benefits later.

If they don't understand that, you either need to work on teaching them that or work on polishing your resume.

Title: How to Deal With The "Automation is Easy" Mindset?

Body:
The title says it all. Some employees in our company believe that automated tests are "easy" and that it "should take a day" to write suites of COM and UI tests. What can be done to counter this? </p>

<p>Note: I'm not asking about how to promote automation. That isn't the problem. Automated testing and processes are being promoted and requested all the time here. The issue is that some individuals don't understand that automation is not "easy" nor is it "fast". </p>


答:
Next time you get a request try to break down as much of the automation process down into chunks of time. I think when they realize that it takes 5 minutes per text field or button push they start realizing how long it takes.

For instance, maybe why it takes so long is that they start introducing interdependence among the fields: e.g. only allow them to proceed if this is filled out but not if this this aren't, except when....

Try to educate them on WHY it takes so long, but not so much as you lose them through the "learning" process.


答:
Most employees spend their time in either the "front" (client- boss- stakeholder- facing) part of the company or the "back," (where the "real" work gets done). These two functions are different, almost opposite. (And very few people have worked in both). As a result, there are often misunderstandings between the two groups.

The best way to educate e.g. "front" people, is to have one or a few of them spend a day in the "back." If they completed "A day in the life of...," they would have a more realistic idea of what can be done in a day, and why it takes more time and effort to run automated tests. Likewise, "back" people could benefit from a day or two at the "front."

In "How to be Rich," John Paul Getty (a tycoon for his time) advocated such "cross-training." In his view, a salesman who spent time on the assembly line where the product was manufactured would do a much better job of selling, and likewise an engineer who spent a day with clients would do a better job of "debugging."


问:
help me understand Rails and attributes as class methods
This is from the Hartl Rails tutorial. We are automatically logging in a user in the process of creating that user with a callback to #create_remember_token. It works great but there are some things, I am not clear on. Please bear with me as I'm thoroughly confused to the point that I don't even know how to ask my question.

I have a user model:

```<code>class User<ActiveRecord::Base
...
...

before_create :create_remember_token
def User.new_remember_token
  SecureRandom.urlsafe_base64
end

def User.encrypt(token)
  Digest::SHA1.hexdigest(token.to_s)
end

private

  def create_remember_token
    self.remember_token = User.encrypt(User.new_remember_token)
  end
</code>```

...

I am confused about the ::new_remember_token and the encrypt being methods attached to User. It looks as though they are attributes of User like name, email, password etc, because they are being accessed with dot notation. But they are defined like methods and seem to return a computed value. I don't understand, why an attribute of the User model is referred to with self for assigning self.remember_token and User.encrypt for accessing the class method.

My question

What's the difference between the above and the following where User, is replaced with self. ?

```<code>class User<ActiveRecord::Base
...
...

before_create :create_remember_token
def new_remember_token
  SecureRandom.urlsafe_base64
end

def encrypt(token)
  Digest::SHA1.hexdigest(token.to_s)
end

private

  def create_remember_token
    self.remember_token = self.encrypt(self.new_remember_token)
  end
</code>```

...

I'm a novice in the ruby language, but pretty good with javascript, so if there's a js analog it might help me to put it in those terms.

答:
You're currently working on the User model within ruby as you look down you code you can see

def function

end

That creates a function that exists within the User class, so in theory from most anywhere else in your application you could do User.some_function, you only use self.some_function from within the class.

There isn't any difference between using User.encrypt and self.encrypt except that its safer,  self.function means only look inside the current class.

I think you're probably getting attributes and functions mixed up because you're not seeing the () at the end of function calls, you don't actually use those in ruby unless you passing parameters to the function.

Where you're mentioning username, password, email etc those are fields associated with the database and are attributes.

The concept to understand here is that the User model represents the association with the underlying database, you can(as you have there) add extra functionality to ensure the quality of the data going in for example:

```<code>before_create :create_remember_token
</code>```

That means that if ANYWHERE within you application you create a new user the model calls that function as part of the process of creating the record. Essentially by building functionality into models you can ensure that all data going into the database is treated in the same way.

Body:
You're currently working on the User model within ruby as you look down you code you can see

def function

end

That creates a function that exists within the User class, so in theory from most anywhere else in your application you could do User.some_function, you only use self.some_function from within the class.

There isn't any difference between using User.encrypt and self.encrypt except that its safer,  self.function means only look inside the current class.

I think you're probably getting attributes and functions mixed up because you're not seeing the () at the end of function calls, you don't actually use those in ruby unless you passing parameters to the function.

Where you're mentioning username, password, email etc those are fields associated with the database and are attributes.

The concept to understand here is that the User model represents the association with the underlying database, you can(as you have there) add extra functionality to ensure the quality of the data going in for example:

before_create :create_remember_token

That means that if ANYWHERE within you application you create a new user the model calls that function as part of the process of creating the record. Essentially by building functionality into models you can ensure that all data going into the database is treated in the same way.


答:
In my roles i've come across many "x is easy" people especially on development projects. In my mind there are three reasons for this:

1) They really don't understand what they're talking about but very much like to sound like they do.

2) They've read a couple of books and think they know what they're talking about

3) Lastly people assume because a computer is doing the testing its fast, because computers are fast.

The one sure fire way to combat this is to engage users on a regular basis, communication strategies for projects are key, certainly explaining the ins and outs of automated testing to non technical users is going to be futile but making them aware of the processes involved can be beneficial. You can do this either via documentation, workshops or just a friendly chat next time your passing through.

I've even seen a BA single out the loudest of these "x is easy" people and simply invite them down for a day in the department, with the thinking they'll either walk away understanding more about what you do OR they'll simple come away thinking "god I really don't know what i'm talking about, I think I was wrong".


答:
2 +2 = 4 is one of the most simple piece of code that everybody understand; And you can see how is easily understand. But this does not mean it's a “easy” equation. The level of abstraction that are needed to reach the simple equation is quite complex. Same happens with the software and software testing methodologies. The level of abstraction that requires a piece of code takes a lot of work.

It is true that a good practice leads to reuse classes and objects but equally, to reach this state is necessary to invest time and effort.


问:
How to approach multiple page form with just one save option
The screen shot shows the magento product upload page.

The left nav allows you to switch to different options for the product. Basically each option in the left nav appears as a different page. However when you save and close, it will save all the updates made on each page.

Using Foundation4, html, css, js - what would be the best approach to replicating something similar? Say I want 3 pages and one save button option.

Using http://foundation.zurb.com/docs/components/section.html#panel2 and having the save buttons the top line form level seems a possible option.

答:
Perhaps you should re-think your design.  Instead of displaying options on a separate page, display them within a div. And if you need to display more info than the div has room for, display it in a floating hidden div that you fill, show and hide when appropriate.   That way everything remains on one page.

I can think of umpteen relatives who would be confused with tabs.  When purchasing something they tend to assume:
1) there is only 1 submit/save button;
and 2) a running total is being displayed in the right hand column.


答:
Leave joking:

Mergesort certainly is a good candidate to implement a parallel algorithm.

A general algorithm for parallel sorting could be like this :

Divide the data in k junks (where k is the number of processing agents).

Sort each junk in parallel.

Merge the sorted junks.

As @amon points out in his comment, the third step can even be executed partly in parallel with step 2, if the sort algorithm selected returns the small elements first.


问:
Are There Other Use Cases For F# Type Providers?
So I think I know the main use case for F# 3.0's Type Providers, i. e. better Intellisense when working with data stores that use them.  Are there other use cases for Type Providers or is that pretty much it? </p>

答:
There are F# Type Providers for things other than what is traditionally thought of as data.

One example is the FunScript type provider:

FunScript is a lightweight F# library that lets you rapidly develop
  single-page applications. You can connect to external data sources and
  call REST APIs with intellisense, produce dashboards using JavaScript
  visualization libraries and write asynchronous computations easily
  without explicit callbacks.

Another one is the F# R type provider:

An F# type provider for interoperating with R.

So you can see that type providers can be used to provide interoperability to other programming languages (JavaScript and R shown here).


答:
If it's for web servers, just use IP address and domain name. Those are some informations used to create SSL certificate for HTTPS.

In fact, you can use HTTPS method for validation. In your case your application would be like a web browser trying to validate the server by contacting Certificate Authority, in your case, your license server.

This will reduce maintenance issue to slightly more than updating SSL certificate, which is an acceptable pain when changing IP address or domain name.

Title: Use MAC address for license

Body:
One of my company product need to implement a license mechanism. I'm planing to generate a key  base on users PC MAC address. But I'm bit scared is this method confuse with some advance hardware. configurations such as.

Multiple network cards.

Virtualization.

Mac address change possibilities(?)

Working with VPNs.

Is it a good idea to generate license key with MAC address? Some ideas?


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答: Erlang is in use at Facebook, Yahoo, and Amazon. It's also running embedded in Ericsson and Nortel ePBX (electronic Public Branch Exchange) telecom switches with ridiculous uptime. CouchDB is written in Erlang, as is ejabberd. There are more now, and more coming every day. Check out Totally Erlang for Erlang jobs to see who's working on what.</p>


问:
Does F# offer anything particularly useful for database-driven web development?
My organization finally upgraded to MS Visual Studio 2010 this year.  One of the big new features that Visual Studio 2010 offers is the F# programming language.

I understand that F# offers a functional programming paradigm, similar to Lisp.  Unlike Lisp though, F# is compiled into managed code for the .net framework.

Right now, I work in database-driven web application development.  Right now, I'm working with an n-tier application with SQL code on the back end and a C#.net AJAX web application on the front-end.  I would like to know if F# offers anything that would be particularly useful for this type of development.

答:
One feature that the latest version of F# has that C# does not is Type Providers.

The types provided by F# type providers are usually based on external
  information sources. For example, an F# type provider for SQL will
  provide the types, properties, and methods you need to work directly
  with the tables of any SQL database you have access to. Similarly, a
  type provider for WSDL web services will provide the types,
  properties, and methods you need to work directly with any WSDL web
  service.

The SQL Server type provider is particularly easy to use. Here is a walkthrough on how to use it.


问:
Use MAC address for license
One of my company product need to implement a license mechanism. I'm planing to generate a key  base on users PC MAC address. But I'm bit scared is this method confuse with some advance hardware. configurations such as.

Multiple network cards.

Virtualization.

Mac address change possibilities(?)

Working with VPNs.

Is it a good idea to generate license key with MAC address? Some ideas?

答:
Thats actually pretty easy for web.

1) Have your license server expire the keys every 24/72 hours

2) When its due to expire your license server gives domains a new key by looking up the domain name and executing a script that comes with your installation:

```<code>https://www.somecustomer.com/yoursoftware/license.php?somekey=hash
</code>```

You can get fancy here by having private keys that only the installation and the server have, then decryption the hash with that private key, obviously if one of your customers gets hacked your going to need to change the private keys but thats simply a matter of building in an update mechanism.

When receiving a new key the endpoint immediately checks with the server that its            actually a genuine update request, this will stop people bricking installations by submitting bogus key updates.

3) during the normal course of operation the software it'll check if it has a valid key by contacting the server

That way the only way it can go wrong is if the domain gets hijacked which to be fair isn't your problem.

Title: Use MAC address for license

Body:
Thats actually pretty easy for web.

1) Have your license server expire the keys every 24/72 hours

2) When its due to expire your license server gives domains a new key by looking up the domain name and executing a script that comes with your installation:

https://www.somecustomer.com/yoursoftware/license.php?somekey=hash

You can get fancy here by having private keys that only the installation and the server have, then decryption the hash with that private key, obviously if one of your customers gets hacked your going to need to change the private keys but thats simply a matter of building in an update mechanism.

When receiving a new key the endpoint immediately checks with the server that its            actually a genuine update request, this will stop people bricking installations by submitting bogus key updates.

3) during the normal course of operation the software it'll check if it has a valid key by contacting the server

That way the only way it can go wrong is if the domain gets hijacked which to be fair isn't your problem.