答:
Users most times know exactly their daily work and which problems they have to solve. What they typically don't know is

a) how the software exactly has to look like to support that process.

b) how they can explain their process to you.

So focus on questions to understand what the user really want (their goals, their working process), and not if a button should be blue, red, on the left or the right side of the dialog box. Often it is not so much important too clarify any ambiguity, but the right ambiguities.

Concerning "low level details": avoid that during the meeting - often there are different solutions for achieving the same goal, with different low level details, different costs / development effort, different feasibility. To my experience, it is much better to think a while over the requirements (after the meeting!), and suggest a feasible solution later on, when you made a thorough analysis of the requirements.

And try to avoid worrying about the potential development effort for specific requirements (at least, not during the meeting). Only writing all the requirements down does not mean they will have to be implemented 1:1. After your meeting, you or the team will get a chance to analyze them, make estimations for the implementation (probably different estimations for different possible solutions for the same requirement), and afterwards the requirements will be prioritized or discussed again. What you should avoid is to tell the people any estimations during the meeting out of your stomach, even if they ask or try to pressure you. Just say "I will give you an answer later".

Title: What is the ideal mindset for a developer participating in a requirements gathering meeting?

Body:
As a mid-level developer on my team, I participate in requirements gathering/scope planning meetings of projects that I will be part of. I have been finding it difficult to come up with the questions that add value to the discussion or to my knowledge. After some self analysis, I found that knowing that there is a senior engineer in charge of the project who would lead the discussion, has caused me to be laid back in some of these discussions. But I do want to get to a point where I am entrusted with more responsibility and gain skills to handle projects on my own. Though mindset is a bit abstract term to ask about, I would like to get some advice on few things listed below:

What kind of preparation will I need to gain most out of these meetings. From observations from team members, I noticed that understanding what all systems that the project is going to impact, What business decisions will majorly impact the project design etc. are some of them.

Do I need to avoid thinking about low level implementation details for every requirement. On one hand, I feel it's important to consider them because I will know about the feasibility but I also understand it hinders considering all choices.

Finally, as a developer, what is something that I should not be worried about?


问:
How much does C help you in other languages?
How much does learning C to moderate level help you as a programmer. For example, does being competent in C make it easier to pick up languages as time goes on and get a better understanding of them?</p>

答:
Learning C will only help you in learning languages which are very much like C. But then, what do you gain from you learning them? The further away from C the language you want to learn is, the less learning C will help you.

In particular, C is missing a lot of concepts, paradigms and ideas that are present in more modern languages: first-class procedures, Objects, Algebraic Data Types, parametric polymorphism, ad-hoc polymorphism, inclusion polymorphism, subtyping, inheritance, delegation, concurrency, parallelism, asynchrony, modularity, first-class control flow (e.g. continuations), static compile-time metaprogramming, dynamic metaprogramming, higher-kinded types, rank-n types, dependent types, type inference, dynamic typing, EDSLs, … (those are just a few that spring to my mind).

ContentLicense: CC BY-SA 3.0


问:
Big-O notation for other cases
I was just reading answers to a question Plain English explanation of Big O
From that i came to know that Big-O notation is just an "upper bound" of the complexity of an algorithm?

But can we apply it to other cases(i.e best and average case) of an algorithm?

答: Big-Oh describes the growth rate of a set of functions by comparing it to the growth rate of another function. What those functions mean is totally irrelevant to Big-Oh. It could be a function describing the worst-case time complexity of an algorithm. It could be a function describing the best-case time complexity of an algorithm. It could be a function describing the average case time complexity of an algorithm. It could be a function describing the amortized worst-case time complexity of an algorithm. It could be a function describing the worst-case step complexity of an algorithm. It could be a function describing the worst-case space complexity of an algorithm. It could be a function describing the amount of humans in the world. It could be a function describing the amount of money a movie makes in relation to its production cost.

Title: Big-O notation for other cases


答: Learning C or something similar, such as Pascal, may help you to understand how the compiler, linker, and run-time libraries work together, so you can better understand the low level details of computer systems. This was my experience when comparing the output of a C compiler to assembly code. C will not help much with higher level language ideas, which are easier to use in other languages, such as those described by Jörg W Mittag.</p>

Title: How much does C help you in other languages?

Body: How much does learning C to moderate level help you as a programmer. For example, does being competent in C make it easier to pick up languages as time goes on and get a better understanding of them?</p>


问:
How to structure a loop that repeats until success and handles failures
I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another 1/2 right now.

In the classes we are learning to program in C++ (which is a language that I already knew to use quite well before we started).

I have not had any difficulties during this class but there is one recurring problem that I have not been able to find a clear solution to.

The problem is like this (in Pseudocode):

```<code> do something
 if something failed:
     handle the error
     try something (line 1) again
 else:
     we are done!
</code>```

Here is an example in C++

The code prompts the user to input a number and does so until the input is valid. It uses cin.fail() to check if the input is invalid. When cin.fail() is true I have to call cin.clear() and cin.ignore() to be able to continue to get input from the stream.

I am aware that this code does not check of EOF. The programs we have written are
  not expected to do that.

Here is how I wrote the code in one of my assignments in school:

```<code>for (;;) {
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        continue;
    }
    break;
}
</code>```

My teacher said was that I should not be using break and continue like this. He suggested that I should use a regular while or do ... while loop instead.

It seems to me that using break and continue is the simplest way to represent this kind of loop. I actually thought about it for quite a while but did not really come up with a clearer solution.

I think that he wanted me to do something like this:

```<code>do {
    cout << ": ";
    cin >> input;
    bool fail = cin.fail();
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (fail);
</code>```

To me this version seems alot more complex since now we also have variable called fail to keep track of and the check for input failure is done twice instead of just once.

I also figured that I can write the code like this (abusing short circuit evaluation):

```<code>do {
    cout << ": ";
    cin >> input;
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (cin.fail() && (cin.clear(), cin.ignore(512, '\n', true);
</code>```

This version works exactly like the other ones. It does not use break or continue and the cin.fail() test is only done once. It does however not seem right to me to abuse the "short circuit evaluation rule" like this. I do not think my teacher would like it either.

This problem does not only apply to just cin.fail() checking. I have used break and continue like this for many other cases that involve repeating a set of code until a condition is met where something also has to be done if the condition is not met (like calling cin.clear() and cin.ignore(...) from the cin.fail() example).

I have kept using break and continue throughout the course and now my teacher has now stopped complaining about it.

What are your opinions about this?

Do you think my teacher is right?

Do you know a better way to represent this kind of problem?

答:
I would write the if-statement slightly different, so it is taken when the input is successful.

```<code>for (;;) {
    cout << ": ";
    if (cin >> input)
        break;
    cin.clear();
    cin.ignore(512, '\n');
}
</code>```

It's shorter as well.

Which suggests a shorter way that might be liked by your teacher:

```<code>cout << ": ";
while (!(cin >> input)) {
    cin.clear();
    cin.ignore(512, '\n');
    cout << ": ";
}
</code>```

Body:
I would write the if-statement slightly different, so it is taken when the input is successful.

for (;;) {
    cout << ": ";
    if (cin >> input)
        break;
    cin.clear();
    cin.ignore(512, '\n');
}

It's shorter as well.

Which suggests a shorter way that might be liked by your teacher:

cout << ": ";
while (!(cin >> input)) {
    cin.clear();
    cin.ignore(512, '\n');
    cout << ": ";
}


问:
Fixed scope and resources - but I am being asked for an exact release date
We have a project where the scope and resources are fixed.

We have a fully groomed backlog and a velocity, so from this I can work out a rough idea of when we may release.

As a team, we feel it is understandable that the business will want some idea of when it will be released.

My approach is to say something along the lines that based on the backlog size and velocity, we are looking at around 3 sprints until we can release say.  But that is a rough estimate, and it is based on quality and any unforeseen issues that we can't predict.

The company though (especially the Product Manager) expects the team to agree to a precise date i.e. it's now early January, we commit to releasing it on the 28th March.

I am aware of principles such as the iron triangle, and how you can't fix all three sides.

Given this scenario, how do other development teams answer this sort of request, as in you have fixed scope, you have fixed resources, and you are being asked to give an exact release date?  Do you refuse to give any estimate, give a rough estimate, or agree to somehow commit to a precise date?

答:
Triage the scope, so that the most important features/requirements are completed first. Make the project "releasable" at least every week or so, so that if your funding is cut off mid-point, you don't have a complete failure.

By the way, this is standard practice for experienced development managers/leaders, as it is rare to finish everything by the deadline, if the deadline is fixed and optimistic.


问:
Implicit Conversion Operators for Value Types in C#
I’ve come across this blog article: Implicit Conversion Operators are Bad. The article discourages the use of implicit conversion with reference types. The article describes problems caused by implicit conversions of reference types, which boils down to the following

[...] main question of this post: why are implicit conversion operators bad on reference types?
  [...] By adding an implicit conversion operator to a reference type, you have now introduced value semantics to assignments – but only from one type to another.

  [emphasis original]

My question, however, is about value types.  In the beginning, the article has got this statement:

Implicit conversion operators are incredibly important to the language, but only for value types.

  [emphasis original]

The article doesn’t go into details on how to use implicit conversion with value types.  That is what I’m wondering about.  Here's my present thinking:

The conversion operator is on a value type, and it returns a value type.  Implicit - okay.

The conversion operator is on a reference type, and it returns a value type.  Implicit – okay.

The conversion operator is on a value type, and it returns a reference type.  (That would be a somewhat bizarre, but would it be wrong?)  Implicit – not okay.

The conversion operator is on a reference type, and it returns a reference type.  Implicit – not okay.

In a more compact form:

If it returns a value type, an implicit conversion operator is okay on both value type and reference type.

If it returns a reference type, implicit conversion is not okay.

Is this correct?  Is this complete?

p.s.  For the most part, I work mostly with C and C++, where I have fine control over things like const, pointers, references.  Of course, that comes at a risk of contracting nasty pointer-related bugs.

答: If you stick to immutable reference types, they have the same value semantics as value types, and the restrictions disappear. I have never used conversion operators for mutable reference types, as I only use them in cases where value semantics makes more sense.</p>


问:
Should benchmarks (to compare processors performance) be compiled with optimization CFLAGS?
I need to compare performance of 2 processors and I concluded I should benchmark then with several various tests.

I'm currently using

linpack (HPL) (because it's still well known and used for example to build top 500 list)

SciMark2 (because of 5 different methods inside)

simple for loops written in C (to see difference between simple instructions / more sophisticated calculations)

Compiling them I saw huuge difference in performance if they are compiled with some *FLAGS  (-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4).

Should I be using these optimization flags or not to get my point?

I'm afraid I'm loosing some point / differ benchmarks between architectures when optimizing.

答: You should use the compilation options you would use when actually compiling the programs that this benchmark is standing for. Computation-intensive programs are usually compiled with optimization (unless you are researching the efficacy of optimization), and so the benchmarks should be compiled with optimization.</p>

OwnerDisplayName: KaP

OwnerDisplayName: Yuval Filmus


答:
I am somewhat puzzled; please bear with me.  It would appear to me that you are in a pretty ideal situation that most dev managers can only dream about!  You have fixed scope (who has seen in that in this day and age of constantly changing business requirements?!), you have a dedicated team (ditto!) and you have experience working with the team - so their velocity is known/ generally understood.

If the velocity is know, it must already take into account the quality they can deliver, the amount of rework they may have had to do in the past, and the 'net' delivery rate or 'net velocity'.  You really can't do much about unforeseen issues as of now - except to provide for some contingency - which, ideally, you might be able to do from past experience with project schedules and overruns.  Perhaps the scope might expand.  Or a team member might fall sick for a week or two.  A 10-20% schedule contingency might be in order.

So where is the problem? Or am I missing something?  What possible unknowns are you worried about? I would think it should be possible for you - based on your release/ sprint plan - to forecast a completion date, with a contingency factor (or a confidence factor for a specific date).

As long as you provide an overall rationale, I am not sure what objections could your Product Owner or other management reps come up with for the plan you provide. They are asking for a fixed date, they will get one, with some contingency thrown in.

Not sure this is helping you any - since it is all pretty obvious - but hope it does.

I do agree with @Frank's suggestion - do keep prioritizing regularly with the product owner - giving them the benefit of the ability to change their mind about some of the priorities - and in fact even dropping some stuff altogether - while adding new stuff into the backlog, while keeping overall scope unchanged by and large.  One of the key principles of Kanban, of which I am a big proponent, is this ability to reprioritize till the 'last responsible moment', focusing on the most important stuff at any point in time, delivering often and helping the customer get the important stuff on time.

Title: Fixed scope and resources - but I am being asked for an exact release date

Body:
We have a project where the scope and resources are fixed.

We have a fully groomed backlog and a velocity, so from this I can work out a rough idea of when we may release.

As a team, we feel it is understandable that the business will want some idea of when it will be released.

My approach is to say something along the lines that based on the backlog size and velocity, we are looking at around 3 sprints until we can release say.  But that is a rough estimate, and it is based on quality and any unforeseen issues that we can't predict.

The company though (especially the Product Manager) expects the team to agree to a precise date i.e. it's now early January, we commit to releasing it on the 28th March.

I am aware of principles such as the iron triangle, and how you can't fix all three sides.

Given this scenario, how do other development teams answer this sort of request, as in you have fixed scope, you have fixed resources, and you are being asked to give an exact release date?  Do you refuse to give any estimate, give a rough estimate, or agree to somehow commit to a precise date?


问:
How should I structure an application containing business logic and display?
I'm working on a simple board game that will run in the browser. I'm thinking how to structure the program and I'd like to hear your opinions.

The program will consist of the user interface part (the logic that handles key presses, manipulates Html, etc.), and of the data-and-logic part (makes decisions on how to update the game and stores the state of the game).

I can think of two options regarding how to structure this:

A- The business logic module references the display module.

Advantages:

The display knows nothing about the business logic.

Easy to inject the display to the business logic.

Disadvantage: how can the business logic be notified when the user performs an action?

B- The display module references the logic module.

Advantage: the display can easily notify the business logic when the user performed an action.

Disadvantage: the display knows about the existence of the business logic.

Which design is better, and why?

答:
Advantages: The display knows nothing about the business logic.

You can't display something you know nothing about. Trying to invert control so the business logic calls some sort of display API just turns part of the business logic into display logic and intertwines the two. Then your business logic will break if the display API or display logic ever changes.

Approach B is the better approach and is the basis for the Model-View-Controller architecture.


答:
You are a software developer! Don't answer misleading questions! Instead, help your manager to ask the right question. Then, answer the good question.

When will my feature be ready? is a misleading question. Examples of good questions are:

What's the probability of having my feature in three months?

What's the date by which I will have my feature ready with a probability of 70%?

Now, how would you answer these questions once they are asked? Well, you will have to use your records to build an empirical probability distribution of the random variable DevTime. I've done this myself and have found that Lognormal distributions have an excellent fitting.

A Lognormal distribution has two parameters: mean and standard deviation. Alternatively you can define them by providing mean and the dispersion P90/P10.

There are many approaches to find out good estimates of the mean and the dispersion. If you have data of other projects with similar scope, use them and use some curve fitting algorithm (e.g., BoxCox.)

If you want to be more rigorous you will need to build some model that should take into account the following uncertain factors:

Size of project

Focus - % resources you will allocate for the project (you have other tasks, right?)

Endurance - % of lines of code integrated that survived, say, >= 6 months

Speed - Lines of code (or # classes) produced by the team / day.

For the size I've used the number of classes involved as a proxy, have put a Triangular Distribution around it, and have multiplied this random variable by the (empirical) distribution of #menthods/class.

The focus is easier, I would start with 40%. You can use this parameter to negotiate with your manager.

What I've called endurance is measurable from your historical data. Again, don't use an average, compute the empirical probability distribution of this quantity.

Same for speed.

With all these distributions is fairly easy to build a probabilistic model and run Monte Carlo on it. That will give you the values of mean and dispersion you were looking for.

Once you have the distribution, plot it and teach your manager how to read it. The answer to all the questions that make sense will be right there.

If you don't have any data, or you don't have the time & resources to build the model I'm proposing, then play with your best "expert" estimates of the mean and dispersion and use some app to plot the resulting Lognormal distribution. Once you feel confident with one curve, use that for your poor-man estimations.

Bottomline: Don't answer silly questions. Turn them in good ones that will provide insights.


答:
Should I be using these optimization flags or not to get my point?

What is exactly your point? It really depends on what you want to prove and even if you try to make an honest comparison, people know all benchmark should be taken with some grains of salt.

Some examples:

linpack test won't be comparable to top 500 list because they run the jobs on GPU, not CPU, and the result is FLOPS. Is FLOPS what you're after?

do the CPUs have same cache size? There are ways to exploit this difference

simple loops written in C might not show difference in CPU-memory bus speeds.

In any case, usually every test is run in tuned environment to get maximum performance. What tunings used can be different as long as there's a proper disclosure about them. If they're only tuned to what linux is compiled with, someone might dispute that different results can be achieved using different set of parameters.

SPEC CPU is probably what you after. It consists of integer and floating point suites. It's not cheap, probably why GeekBench is more popular these days (not free, but still cheap). I certainly wouldn't want to read too much into other benchmarks results.

Title: Should benchmarks (to compare processors performance) be compiled with optimization CFLAGS?

Body:
I need to compare performance of 2 processors and I concluded I should benchmark then with several various tests.

I'm currently using

linpack (HPL) (because it's still well known and used for example to build top 500 list)

SciMark2 (because of 5 different methods inside)

simple for loops written in C (to see difference between simple instructions / more sophisticated calculations)

Compiling them I saw huuge difference in performance if they are compiled with some *FLAGS  (-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong --param=ssp-buffer-size=4).

Should I be using these optimization flags or not to get my point?

I'm afraid I'm loosing some point / differ benchmarks between architectures when optimizing.


问:
Where does test fixture code fit in?
This is an unusual question since I don't believe it lends itself to typical software development practices but I hope you can prove me wrong.

In MATLAB, my team have created several signal processing components, where data goes in one end, and different data comes out the other. What each of the components do is unimportant at this stage. What matters is that the typical testing pattern my team have adopted is that they write a script which generates the input data (each around 40MB in size), and then they run each test file through the applicable component (scripted). How they determine that their component passes the test or not is complete signal processing wizardry to me but lets assume its correct.

Typically, test data is generated only once and takes about half a day to do so. The test themselves can take anywhere up to day to run.

Coming from more of an application development background, and being given the task of integrating each component into a so-called "reference chain", I need to try and standardize testing and make it fool proof. One thing I wanted them to do is to use the unit testing framework to wrap their tests up into. The unit testing framework in MATLAB is, for the purposes of this question, just like JUnit.

My question is where does the scripts that generate the test data, and the test data itself fit in to the test ecosystem. Obviously the test data is a fixture, and can be treated as such, but I am a bit nervous about where the scripts that generate the test data fit in.

I would also welcome any critiques of my team's testing approach.

答:
First, I think it's good to state what's important. I'm familiar with "continuous integration" types of build systems, so I think that 1) Checking in everything necessary to build, 2) Building from a remote system in an automated way to prove #1, and 3) Testing in automated fashion - are all important. If you have different values, you may come to a very different conclusion.

Based on those values, I see the test data as a dedicated build target, along with one for building the MATLAB code, and one "overall" target for building both and running the test. This doesn't mean that the test data needs to be regenerated every time - something like "make" may be better suited for this type of checking. Since the tests themselves take a day to run, the initial hit of half a day to generate the data may not even be so bad with respect to the big picture. And of course if needed the test data itself can be checked in as a build artifact but you may want to build from scratch every time you do a release.

Title: Where does test fixture code fit in?


答:
It's not so much that for(;;) is bad. It's just not as clear as patterns like:

```<code>while (cin.fail()) {
    ...
}
</code>```

Or as Sjoerd put it:

```<code>while (!(cin >> input)) {
    ...
}
</code>```

Let's consider the primary audience for this stuff as being your fellow programmers, including the future version of yourself who no longer remembers why you stuck the break at the end like that, or jumped the break with the continue. This pattern from your example:

```<code>for (;;) {
    ...
    if (blah) {
        continue;
    }
    break;
}
</code>```

...requires a couple seconds of extra thought to simulate versus other patterns. It's not a hard and fast rule, but jumping the break statement with the continue feels messy, or clever without being useful, and putting the break statement at the end of the loop, even if it works, is unusual. Normally both break and continue are used to prematurely evacuate the loop or that iteration of the loop, so seeing either of them at the end feels a little weird even if it's not.

Other than that, good stuff!

Title: How to structure a loop that repeats until success and handles failures

Body:
I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another 1/2 right now.

In the classes we are learning to program in C++ (which is a language that I already knew to use quite well before we started).

I have not had any difficulties during this class but there is one recurring problem that I have not been able to find a clear solution to.

The problem is like this (in Pseudocode):

```<code> do something
 if something failed:
     handle the error
     try something (line 1) again
 else:
     we are done!
</code>```

Here is an example in C++

The code prompts the user to input a number and does so until the input is valid. It uses cin.fail() to check if the input is invalid. When cin.fail() is true I have to call cin.clear() and cin.ignore() to be able to continue to get input from the stream.

I am aware that this code does not check of EOF. The programs we have written are
  not expected to do that.

Here is how I wrote the code in one of my assignments in school:

```<code>for (;;) {
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        continue;
    }
    break;
}
</code>```

My teacher said was that I should not be using break and continue like this. He suggested that I should use a regular while or do ... while loop instead.

It seems to me that using break and continue is the simplest way to represent this kind of loop. I actually thought about it for quite a while but did not really come up with a clearer solution.

I think that he wanted me to do something like this:

```<code>do {
    cout << ": ";
    cin >> input;
    bool fail = cin.fail();
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (fail);
</code>```

To me this version seems alot more complex since now we also have variable called fail to keep track of and the check for input failure is done twice instead of just once.

I also figured that I can write the code like this (abusing short circuit evaluation):

```<code>do {
    cout << ": ";
    cin >> input;
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (cin.fail() && (cin.clear(), cin.ignore(512, '\n', true);
</code>```

This version works exactly like the other ones. It does not use break or continue and the cin.fail() test is only done once. It does however not seem right to me to abuse the "short circuit evaluation rule" like this. I do not think my teacher would like it either.

This problem does not only apply to just cin.fail() checking. I have used break and continue like this for many other cases that involve repeating a set of code until a condition is met where something also has to be done if the condition is not met (like calling cin.clear() and cin.ignore(...) from the cin.fail() example).

I have kept using break and continue throughout the course and now my teacher has now stopped complaining about it.

What are your opinions about this?

Do you think my teacher is right?

Do you know a better way to represent this kind of problem?

Body:
It's not so much that for(;;) is bad. It's just not as clear as patterns like:

while (cin.fail()) {
    ...
}

Or as Sjoerd put it:

while (!(cin >> input)) {
    ...
}

Let's consider the primary audience for this stuff as being your fellow programmers, including the future version of yourself who no longer remembers why you stuck the break at the end like that, or jumped the break with the continue. This pattern from your example:

for (;;) {
    ...
    if (blah) {
        continue;
    }
    break;
}

...requires a couple seconds of extra thought to simulate versus other patterns. It's not a hard and fast rule, but jumping the break statement with the continue feels messy, or clever without being useful, and putting the break statement at the end of the loop, even if it works, is unusual. Normally both break and continue are used to prematurely evacuate the loop or that iteration of the loop, so seeing either of them at the end feels a little weird even if it's not.

Other than that, good stuff!


问:
Best way to deal with Floors and Ceiling when using substitution method to solve Recurrences
I'm currently using substitution method to solve recurrences. The problem I'm having is dealing with T(n) that have either ceilings or floors. For example in the following example see example here.

They end up using the guess: T(n) ≧ c(n+2) lg(n+2)

My first guess was T(n) ≧ n lg(n), which turns out to not work but my problem is I end up having to play around with guess to try get one to work. So questions are as follows:

What is the best way to deal with these floors and ceiling in general?

With regards to guesses, does this come with practice or are there betters ways of deducing the correct guess off the first shot without having to use Recursion Trees.

(PS not sure how to write equations in math notation, its my first time using this forum)

答:
In an attempt to answer question 2, I would like to quote the following

Ultimately, there is only one fail-safe method to solve any recurrence:

Guess the answer, and then prove it correct by induction.

Please check out the following link - https://courses.engr.illinois.edu/cs473/sp2010/notes/99-recurrences.pdf .This describe techniques to generate guesses that are guaranteed to be correct, provided you use them correctly. It was a while ago that I did anything along these lines but I also think following a process in a book as suggested by Andrew is the best solution since it is not something that can quickly be described in a forum post.


答:
Yes, you can apply it to other cases.

Big-Oh basically says "no matter how you stack the deck against this algorithm, at worst its performance will scale this way compared to the input."

Omega is similar, but means "no matter how good you make its inputs, at best its performance cannot scale any better than this compared to the input."

For example, quicksort is a popular sorting algorithm. It is actually O(n2) because at worst it has quadratic performance (bad pivot choice). At best it is Ω(n log2 n) which is actually the best that any general-purpose sorting algorithm can possibly achieve.

Title: Big-O notation for other cases

Body:
I was just reading answers to a question Plain English explanation of Big O
From that i came to know that Big-O notation is just an "upper bound" of the complexity of an algorithm?

But can we apply it to other cases(i.e best and average case) of an algorithm?


问:
Release cycle as a game
I thinking about how increase developer's commitment to release and create release cycle as a game for more fun in office.

Current suggestions

Building tower from bricks

Climbing on some hypothetical everest, where each camp is release stage

Some badges system, like StackExchange system

答: Can't we just have developers who understand why a proper release process is important and do it out of a sense of professional pride?</p>

ContentLicense: CC BY-SA 2.5

Title: Release cycle as a game


问:
GPL and code producing software
I want to make an online management tool for a server software using GPL licensed software. For the tool I'm fine releasing all software to anyone how wants it. After all, it's not rocket science.

The question I have arises when the tool can be used to write code and applications also using the GPL licensed software. The tool is not producing or generating any of the output. That is handled by the server software.

Two ways to get it:

The client buys the software including the server software, installs it locally getting the GPL offerings required for the tool.

It's a SAAS and the client signs up online.

Can the client develop internal applications without them having to release the sources in  these cases?

If not, what problems are there?

答:
I am not a lawyer. You should get one, if you are concerned about possible legal issues.

If your “tool is not producing or generating any of the output” there is absolutely no reason to worry about possible extending of GNU GPL’s copyleft to user’s data.

Even if it would do, that would not be a great problem, you would just have to take certain precautions, similar to that GNU Project took in the case with GNU Bison.

Title: GPL and code producing software


问:
When to Save Assets (mainly Pictures) in DB and when on Filesystem?
For a web application we are planning (some kind of product information system). We have to manage all the assets (pictures) of the products.

There are system (Wikis or DAM System) that save the assets in the DB itself or only a reference.

What are the criterias to decide wheter the files itslef it should be stored on the FS or DB?

The system will manage thumbnails and meta data of the assets.

For a PDF production it is possible that we are going to need them on the FS in other cases it is probably better we have them in the DB.

(We are working in a windows server environment with mongoDB and C#.)

When would it be a disadvantage to have it on the file system (in the DB only meta data)?

Or in which situation clearly wins the DB only approach?

Update

The linked questions brings in some good points.

the concern about backup issues with larger DBs: mongoDB's GridFS is good for larger data. We could have a separated asset DB with another backup interval to solve the problem of the longer backup process.

Serialization and and deserialization to the FS: Could cost a lot of time. In case we need access to them from third party tools (e.g. for PDF production).

答:
It is mostly an opinion-based question (and it is surely operating system and file system specific), however:

you probably want to avoid having a single directory with many thousands of files (it is file system and operating system specific, but some OS & FS may be unhappy), so prefer dir01/subdir02/file0345.txt to justfile01020345.txt

you probably want to avoid having a big lot of very small files (e.g. less than 2Kbytes).

So it might be worthwhile to use a database for "small" contents (e.g. less than half or a few megabytes) and use file for "large" contents (several megabytes each). BTW, you could store in your database some metadata about the large enough file (e.g. at least store something related to the pathname).

You surely need some backup strategy, and perhaps some cleanup strategy too.

Read also about blob-s


答:
This question is handled in the GNU GPL FAQ:

Can I use GPL-covered editors such as GNU Emacs to develop non-free programs? Can I use GPL-covered tools such as GCC to compile them?

Yes, because the copyright on the editors and tools does not cover the code you write. Using them does not place any restrictions, legally, on the license you use for your code.

Some programs copy parts of themselves into the output for technical reasons—for example, Bison copies a standard parser program into its output file. In such cases, the copied text in the output is covered by the same license that covers it in the source code. Meanwhile, the part of the output which is derived from the program's input inherits the copyright status of the input.

As it happens, Bison can also be used to develop non-free programs. This is because we decided to explicitly permit the use of the Bison standard parser program in Bison output files without restriction. We made the decision because there were other tools comparable to Bison which already permitted use for non-free programs.

In what cases is the output of a GPL program covered by the GPL too?

Only when the program copies part of itself into the output.

Title: GPL and code producing software

Body:
I want to make an online management tool for a server software using GPL licensed software. For the tool I'm fine releasing all software to anyone how wants it. After all, it's not rocket science.

The question I have arises when the tool can be used to write code and applications also using the GPL licensed software. The tool is not producing or generating any of the output. That is handled by the server software.

Two ways to get it:

The client buys the software including the server software, installs it locally getting the GPL offerings required for the tool.

It's a SAAS and the client signs up online.

Can the client develop internal applications without them having to release the sources in  these cases?

If not, what problems are there?


问:
Send Emails Via APIs or Code?
I am Using SendGrid to Send Emails to my Users.

There are two ways to send emails via SendGrid.

1 - Via APIs

2 - Via Program/Code

I want to know which one is More Secure and efficient way. I am Using python language, As Python is already slow in processing. So that I want to choose the efficient and fast way.

答:
When you look at the code of the python library, you will notice that it is just a wrapper around the web API. So you are using the web API via python in either case.

Unless you believe that you can write python code which uses the web API much more efficiently than the library does, there is nothing to gain from rolling your own.

Title: Send Emails Via APIs or Code?


问:
What is this Lisp dialect, used in GCC internals?
What programming language is this? It's a Lisp dialect used by GCC internals.

```<code>(define_insn "*call_symbol"
   [(call (mem:DI (match_operand:DI 0 "" ""))
          (match_operand 1 "" ""))
    (use (match_operand 2 "" ""))
    (clobber (reg:DI LR_REGNUM))]
   "GET_CODE (operands[0]) == SYMBOL_REF
    && !aarch64_is_long_call_p (operands[0])"
   "bl\\t%a0"
   [(set_attr "type" "call")]
)
</code>```

Link to source file

答:
It is called machine description files. These .md files are used to generate a significant part of the C (now C++) code of the back end.

BTW, you could also customize GCC using a Lisp-like language: MELT

Some documentation is linked from MELT documentation page, and to get a global picture about GCC I strongly recommend taking several hours on the (Indian) GCC resource center.

This (mine) answer contains pictures which might be helpful to you.


问:
Storing Dates & Times in SQL
I have a tool that I am working on which allows people to create meetings. They can select the Date, Time & Timezone that this meeting is occurring in.

I need to determine the best way to store that data in SQL.

The end goal is that a user can click on "View Meetings" and it will show them all of the meetings. However, they also need to be able to select the timezone that they want to view the meetings in and that needs to changes the times to reflect what they have picked.

What is the best approach to accomplish this?

答:
If you are using SQL Server 2008 or higher, I recommend the DATETIMEOFFSET data type. It stores exactly what you want: date + time + time zone offset. This means that you don't have to write code to translate the value to/from UTC. It also means that no one can forget to translate the value to/from UTC and corrupt the data.

PS: This data type translates directly to the DateTimeOffset data type in .NET code, if that helps.

Title: Storing Dates & Times in SQL


问:
First dedicated IDE?
What was the first program that was created as a dedicated IDE? That is, purpose built for coding, rather than simply allowing integration as part of its expansion options.

This is opposed to a text editor that has generic plugin/add-in/shell features that are were not dedicated to development work.

The features I am thinking about that would qualify an editor as an IDE:

Code highlighting

Integrated compiler invocation (with error reporting)

Code navigation features

(optionally) integrated debugger

Sub question - what was the first Visual IDE? (by which I mean with an integrated GUI designer).

答:
In the mainframe world  (which of course pre-dates the Apple and IBM PC world by decades), there were several on-line editors that were capable of editing source code in several languages - such as COBOL, Assembler and PL/1 as well as "job control language" (JCL).

Some of these editors had features for allowing the display of compiler output on a 3270 visual display. For the OS/VS1 and MVS Operating systems there was ICCF (that ran under CICS) and ISPF.

For full screen interactive debugging there was OLIVER (for CICS applications) and SIMON (for Batch) for DOS/VSE, OS/VS1 and MVS, MVS/XA operating systems. Both OLIVER and SIMON had an ISPF-like interface (for both Operating Systems, including DOS/VSE which didn't have its own native ISPF).Both OLIVER and SIMON allowed in flight changes to data fields and statement "bypassing" on-the-fly, which permitted a limited form of program change.OLIVER also provided automatic memory protection ensuring task isolation and it intercepted all program checks before they even occurred.

It was possible to switch easily between ICCF/ISPF source editing and debugging modes - simply by pressing a Program function key - so it provided a seamless interface that would be recognized as an IDE today. This was from the early 1970's.

If there had been graphic displays freely available in the early 1970's these products would surely have used them to their fullest extent - so it was hardware that was the limiting factor at that time. As it was, colour and foreground/background highlighting were the only ways of identifying important items on screen.

A further point - A comprehensive on-line interactive Spreadsheet application known as The Works Records System was created as early as 1974 using the OLIVER debugging tool. This was at ICI UK - six years before Visicalc for the Apple II.

Title: First dedicated IDE?


问:
What are your opinions on "Gamification"?
I watched an interesting Google Talk video (warning about an hour of your time) about Gamification of whatever you are doing.

It's clear that the StackExchange set of sites employ quite a few of these principles.  There's something compelling about making work fun, but I wonder how many problem domains can incorporate these ideas?  They definitely apply to social applications, but is that all?  The concept of a virtual loyalty program is also quite compelling.

Short description of Gamification:

There is a system of scoring and reward.  For example, Reputation in StackExchange is a type of scoring.  Badges are a type of reward.  The additional priviledges you gain as your reputation goes up are also a type of reward.

An example of a loyalty program with no real redemption would be a promotion that a convenience store did a while back where you buy their products and get FarmVille credits in return.  No real money or goods exchange hands, and the costs to the retailer are minimal at best.  Yet it brings in real money for these virtual paybacks.

Shameless use of JohnL's link: http://en.wikipedia.org/wiki/Gamification

NOTE:
The speaker refers to four classes of users which seem to have become the archetypes.  They are Achievers, Socializer, Explorer, and Killers.  The Achievers would most likely apply to all of us programmers--we like to get things done.  Apparently 80% of people are socializers and like light, non-confrontational interactions.  Explorers go to every corner of a game/application to discover whatever easter eggs and hidden features they can.  Killers not only want to win, they want you to lose and get praise/status for beating you.

答:
It's necessary.

Look at the most popular user based (social?) sites today. Facebook, Twitter, SO / SE, LinkedIn, Reddit. What do they all have in common?

Numbers

On Facebook it's how many friends you have, Twitter how many followers. SO / SE sites are a bit more explicit, they have reputation. LinkedIn is a bit more obscure, they have connections. Its a giant dick measuring contest that works.

By nature we want comparison and judgment. These sites give us that and that is what keeps us coming back. Without that magic number I don't think these sites would be nearly as successful as they are.

Does this mean that sites without a native ranking system are not worth time? No, but it does limit the attraction to being a repeat visitor. Some sites bypass this by offering an valued service. Google for searches, Wired for content, etc. "Gaming" the users is a very effective way of building a user base that has lots of loyalty in terms of repeat visits and contributions. Sites built on these contributions (SO / SE, Facebook, Slashdot...) do much better when they have a number.


问:
Effect of denormalizing
Here's a scenario where I'm wondering whether to denormalize a relational database (MS SQL).

Text description of the requirement

I have users (stored in a users table).

Users belong to Accounts:

An account is created before its users are created

Every user must belong to exactly one account (neither no account, nor more than one account)

Any account may contain many users

A user's assignment to an account is permanent: users are never moved from one account to another

The Users table is predefined so I can't add an "accountId" column to the Users table; so to implement accounts I have:

A Users table, with a userId key

An Accounts table, with an accountId key

A UserAccounts table, with userId and accountId columns (to identify the account associated with each user);
the UserAccounts table is constrained:

Foreign key relations to Users and Accounts table

Uniqueness constraint to ensure that a userId appears no more than once

Because I can't modify the Users table to insert and accountId column in it, I can't ensure that every user has an accountId. And in fact I will insert into the
UserAccounts table after inserting into the Users table, though probably in the same transaction.

I have a dozen other tables (e.g. Sales) which define various types of thing which belong to users

These tables have a userId column (to identify which user each row belongs to)

The problem is that I also need to know what account each thing belongs to

Graphic description of the requirement

Here's a reworded version of the same problem (thanks to MichaelT who suggested this rewording).

```<code>   +-----------+    +--------------+      +--------------+
   | Users     |    | UserAccount  |      | Account      |
   +-----------+    +--------------+      +--------------+
+--> userId pk <----+ userId (uniq)|   +--> accountId pk |
|  |           |    | accountId    +---+  |              |
|  +-----------+    +--------------+      +--------------+
|
|
|  +-----------+
|  | Sales     |
|  +-----------+  (and several other tables like this)
|  | saleId pk |
+--+ userId fk |
   |           |
   +-----------+
</code>```

I can't modify the Users table for various reasons: which is why each user's (single) account is defined using the separate UserAccount table, instead of adding an accountId foreign key to the Users table.

This UserAccount table implements a many-to-one relationship between users and accounts (not a many-to-many relationship). It could be defined using either the following keys:

userId as the primary key

(userId,accountId) as the primary key plus userId as a unique key

The question

Now for the question:

When doing a query against a Sales table that needs to include the Account information, I think there are two ways to implement knowing which account each thing belongs to:

Join the table to the UserAccounts table (to select the accountId for each userId):

```<code>select S.*, UA.accountId
from Sales S
    join UserAccount UA on S.userId = UA.userId
where
    S.something = somethingElse
</code>```

Denormalize the Sales table[s], by storing the accountId in it as well as the userId (the accountId can then be retrieved from Sales without a join to UserAccount):

```<code>|  +--------------+
|  | Sales        |
|  +--------------+  (and several other tables like this)
|  | saleId pk    |
+--+ userId fk    |
   | accountId fk |
   +--------------+
</code>```

If I did the latter I could ensure integrity by defining the userId plus accountId pair/combination as a foreign key constraint into the UserAccounts table (to ensure that the pairing of accountId with userId matches the pairing defined in the UserAccounts table).

```<code>CONSTRAINT Sales_FK FOREIGN KEY (userId,accountId)
    REFERENCES UserAccounts (userId,accountId)
</code>```

I don't have vast experience with database design: I learned it from books (by Joe Celko).

I'm inhibited against denormalizing in general, but denormalizing seems appropriate here: why an extra JOIN in every SELECT statement (to get the accountId), when the same could be obtained by storing the accountId in the table with a (compound or composite) foreign key.

Is there a compelling reason to use (or to not use) either of these two possibilities?

If not then I'm tempted to use the 2nd method:

because it's simpler to define the select statement (without a join)

because it's (presumably) slightly better performance (without a join)

because it ensures that a corresponding row (with an accountId) exists in the UserAccounts table

答:
The point of not denormalizing would be to avoid update anomalies.

Not denormalizing would be good, if and only if:

Users are moved from one account to another

When a user is moved, all the Sales records for that user should implicitly move with the user to the user's new account

In this case, 'denormalizing' is OK for three reasons:

Users are guaranteed to never change accounts

Even if a user did change accounts, we wouldn't want the user's historical Sales rows to change

userId plus accountId are (or could be) defined together (is it called 'compound' or 'composite'?) as a primary key, so defining both together in the Sales table is not denormalizing (they're two physical columns but kind of one logical column)

The denormalizing is PREFERABLE for three reasons (in order of decreasing importance):

It records the historical accountId at the moment when the Sales row is created. The account (not the user) pays for the sale and owns the thing sold, so the mapping from Sales row to Account row must never change in the future even if the user subsequently changes account (which the user never will)

It guarantees that no Sales are inserted for Users which (by an anomaly) have no associated Account

It makes the SELECT simpler: no need to JOIN Sales to UserAccount (instead that JOIN is defined implicitly and at INSERT time by the compound/composite FOREIGN KEY contraint)

I vaguely remember reading that denormalizing is normal, standard, best practice when dealing with historical data: and this might be an example of that kind of "historical" data where denormalizing is justified.

Title: Effect of denormalizing


答:
After reading @DocBrown 's remark that the Wikipedia page on IDE's has a History section with the answer, and @YannisRizos 's objection that the first IDE listed there is not a sourced statement, I scrolled down one further paragraph in that Wikipedia page and read:

Maestro I is a product from Softlab Munich and was the world's first integrated development environment[1] 1975 for software.

where [1] is a bibliography source (in German): "Interaktives Programmieren als Systems-Schlager".  The article is from Computerwoche, a magazine directed at IT managers and CIOs, originally published September 21, 1975.  They describe the Maestro I system as a 'Programm-Entwicklungs-Terminal-System', which translates as 'program development terminal system'.

A 'similar system' is mentioned: 'Stico' from a company called 'ZEDA', which was around a year and half before August 1976, which makes it around February 1975. However, STICO is described in the second linked article as a 'system that creates out of few instructions a complete program and converts it immediately into an executable object program', which looks more like an alternative language, or a set of macros, or a compiler, than an IDE.

In trying to understand which features of Maestro I would classify it as an IDE, it seems the main innovation at the time was the interactive development it allowed:

Maestro fed each keystroke directly to the CPU producing immediate feedback. This feedback was also enabled by the particular characteristics of the hardware, specifically the use of a keyboard and console instead of the earlier punchcards or tape.
  -- http://en.wikipedia.org/wiki/Maestro_I

which makes me wonder what is the difference to a LISP REPL, then.  But hey, I just wanted to overcome the 'cite your sources' problem mentioned above.

Title: First dedicated IDE?

Body:
What was the first program that was created as a dedicated IDE? That is, purpose built for coding, rather than simply allowing integration as part of its expansion options.

This is opposed to a text editor that has generic plugin/add-in/shell features that are were not dedicated to development work.

The features I am thinking about that would qualify an editor as an IDE:

Code highlighting

Integrated compiler invocation (with error reporting)

Code navigation features

(optionally) integrated debugger

Sub question - what was the first Visual IDE? (by which I mean with an integrated GUI designer).


问:
Database design for objects with multiple states
Context

I'm designing a database which, simplified, should be able to handle users sending job requests to each other, and after that a job can be started, finished, and reviewed. The design should be scalable (think millions of users).

Approaches I've considered:

Gargantuan table

One approach, probably not the best one, would be to simply store ALL jobs in one, huge table jobs. This table would need a state column to represent which state the job is currently in (e.g. ACCEPTED, STARTED, FINISHED, REVIEWED e.t.c.). The biggest problem with this approach that I can see is that jobs in different states have different types of data that are relevant to them. For example, a job request has a preliminary agreed upon price, but that could change before the job is started, and change again before the job is finished. This could of course be solved by just adding more columns to the table and naming them properly, but it will probably become a huge bottleneck performance-wise very early to have one table containing all the different types of possible data for all the different possible states of a job.

Different tables for different states

This approach would be to have multiple tables, for example job_requests, jobs_started, jobs_finished, tables who in turn can have substates, e.g. job_requests could have the sub-states PENDING, ACCEPTED, while the jobs_finished table would have the substates COMPLETED, CANCELLED, REVIEWED.

With this approach each table only contains data which is relevant to the current job state, but on the other hand some data might be duplicated (for example the user ids of the job requester, and job receiver -- on the other hand this information could be stored in yet another table?).
The problem with this approach is that I can't think of a good solution on how to archive all the information when transitioning between states. For example, once a job request has been accepted, and then started, it should be deleted from the job_requests table and moved into the jobs_started table, but it's just a matter of time before a stakeholder wants to know for example how long the average time is between a job request being created, until it's been started, at which point I'd need the data from the job_requests table to be able to calculate it.

It feels like this type of problem should be easy to solve, but I really can't think of any good solution which "feels right", any solution I come up with feels ugly and I can immediately think of a number of things which makes the solution bad.

Very grateful for any feedback or tips on approaches I could take. Thanks in advance!

答:
You might want to consider using a noSQL database for this specific data.
This way you can just put your object in a record, no matter what the 'columns' are.

Depending on the chosen database system (and implemented solution), you would be able to 'overwrite' a record with different data if you want. Of course, you can also save your historic data and just PUT a new record in the database.

You can start out with this record:

```<code>myStartedObject{
    id: 1,
    state:  'started',
    agreedUponPrice:    100.00,
    someOtherData:  'x'
}
</code>```

and over time it would change to something like this, or if you want to keep the history records, the id would change.:

```<code>myFinishedObject{
    id: 1
    state:  'finished',
    finishedPrice:  209.00,
    someFinishedData:   'y'
}
</code>```

Storing all state date inside the object is also an option of course, something like this:

```<code>myObject
{
    id: 1,
    states: [{ state: 'started', agreedUponPrice: 100.00, someOtherData: 'x'},
        { state: 'finished', finishedPrice: 209.00, someFinishedData: 'y'}]
}
</code>```

Keep in mind, this surely isn't the silver bullet, but it might be something to consider as you state your 'schema' is quite loose and you don't want to pollute your RDBMS with all of those columns.

Also keep in mind, any RDBMS can do this also. I know in MS SQL you have the XML data type. With this, you can store your data in this XML column. This XML column can contain your deserialized object for instance.
It's not a 'real' noSQL solution, but it looks a bit like one.

Body:
You might want to consider using a noSQL database for this specific data.
This way you can just put your object in a record, no matter what the 'columns' are.

Depending on the chosen database system (and implemented solution), you would be able to 'overwrite' a record with different data if you want. Of course, you can also save your historic data and just PUT a new record in the database.

You can start out with this record:

myStartedObject{
    id: 1,
    state:  'started',
    agreedUponPrice:    100.00,
    someOtherData:  'x'
}

and over time it would change to something like this, or if you want to keep the history records, the id would change.:

myFinishedObject{
    id: 1
    state:  'finished',
    finishedPrice:  209.00,
    someFinishedData:   'y'
}

Storing all state date inside the object is also an option of course, something like this:

myObject
{
    id: 1,
    states: [{ state: 'started', agreedUponPrice: 100.00, someOtherData: 'x'},
        { state: 'finished', finishedPrice: 209.00, someFinishedData: 'y'}]
}

Keep in mind, this surely isn't the silver bullet, but it might be something to consider as you state your 'schema' is quite loose and you don't want to pollute your RDBMS with all of those columns.

Also keep in mind, any RDBMS can do this also. I know in MS SQL you have the XML data type. With this, you can store your data in this XML column. This XML column can contain your deserialized object for instance.
It's not a 'real' noSQL solution, but it looks a bit like one.


问:
SOLID principles vs YAGNI
When do the SOLID principles become YAGNI?

As programmers we make trade-offs all the time, between complexity, maintainability, time to build and so forth. Amongst others, two of the smartest guidelines for making choices are in my mind the SOLID principles and YAGNI. If you don't need it; don't build it, and keep it clean.

Now for example, when I watch the dimecast series on SOLID, I see it starts out as a fairly simple program, and ends up as a pretty complex one (end yes complexity is also in the eye of the beholder), but it still makes me wonder: when do SOLID principles turn into something you don't need? All solid principles are ways of working that enable use to make changes at a later stage. But what if the problem to solve is a pretty simple one and it's a throwaway application, then what? Or are the SOLID principles something that always apply?

As asked in the comments:

SOLID Principles

YAGNI

答:
There is a quote attributed to Einstein (probably a variation on a real one):

“Everything should be made as simple as possible, but no simpler.”

And that is more or less the approach I take when confronted with the SOLID vs YAGNI tradeoff: apply them alternatively, because you never know if a program is 'throw-away' code or not.  So, just add a layer of dirt that works, then polish it to a cleaner interface ... and repeat until you converge to the right level of entropy.  Hopefully.

Title: SOLID principles vs YAGNI


问:
What Scala type to use for a list of meeting participants
I want to store a number of participants for a meeting. The order of them is not important. The only thing I want to make sure is, that I will be able to add and remove participants, use filter functions (and alike) and get their number. Also duplicates are not allowed.
I started using List for the method signature, but now I wonder if I should accept a more abstract type. I saw types like Traversable, TraversableLike, Iterable and IterableLike.

The number of participants will be rather low, usually below 100. Changes will be made occasionally. The participants are immutable (but they have mutable properties e.g. a List of actions they performed for that meeting).

What would be the appropriate abstraction level for my case?

答:
Scala has a lot of collection types that are pretty much only there to allow clever optimizations in the implementation (see Is  the scala 2.8 collections library a case of the longest suicide note in history?).  The ones you actually want to use only have an [A] and nothing else, and generally don't have suffixes like "Like."

If you want something more abstract than a List, try a Seq if you need to index by a number, an Iterable for when you need to create an iterator or take elements from the right, and a Traversable if you don't.

However, generally you would use a concrete type for "internal" storage, where you would be adding and removing elements.  In those cases, you select one based on its performance characteristics, for which a List is most likely just fine in your case.  The more abstract types are more for accepting a collection from other code.


答:
There's many ways to design a program for a given problem; SOLID is an attempt to identify the properties of a good design. Proper use of SOLID is supposed to result in a program that's easier to reason about and modify.

YAGNI and KISS are concerned with feature scope. A program that solves more kinds of problems is more complex and abstract. If you don't need that generality, you've spent time and effort creating code that's harder to understand and maintain but offers no added value.

A program that's designed well isn't necessarily focused on only the features it needs. A program that's focused only on the features it needs isn't necessarily well designed. There is no trade-off, just two orthogonal axes in the decision-making space. An ideal program is both modular and has only essential features.

Title: SOLID principles vs YAGNI

Body:
When do the SOLID principles become YAGNI?

As programmers we make trade-offs all the time, between complexity, maintainability, time to build and so forth. Amongst others, two of the smartest guidelines for making choices are in my mind the SOLID principles and YAGNI. If you don't need it; don't build it, and keep it clean.

Now for example, when I watch the dimecast series on SOLID, I see it starts out as a fairly simple program, and ends up as a pretty complex one (end yes complexity is also in the eye of the beholder), but it still makes me wonder: when do SOLID principles turn into something you don't need? All solid principles are ways of working that enable use to make changes at a later stage. But what if the problem to solve is a pretty simple one and it's a throwaway application, then what? Or are the SOLID principles something that always apply?

As asked in the comments:

SOLID Principles

YAGNI


答:
You mentioned in your comments that your requirements include that:

A) You must be able to add and remove elements from the collection.

B) The order of the elements is not important.

C) Duplicate entries are not allowed.

I would suggest using an immutable Set. It should have effectively constant time additions, removals, and lookups, and will automatically prevent the addition of duplicates. This is probably a better fit than a List, which in Scala requires linear time to update, append to, or lookup in, as it is singly linked and can only be accessed starting from the head.

The syntax for adding and removing from an immutable set is fairly nice as well.

```<code>val xs = Set(alice, bob)
val xs2 = xs + carl              // Set(alice, bob, carl)
val xs3 = xs2 -- Set(alice, bob) // Set(carl)
</code>```

You also get all your typical set operations, like unions, intersects, etc.

As with anything, if you have a large enough set of data that performance really matters, benchmark your results.

Reference: Performance Characteristcs of Scala Collections

Title: What Scala type to use for a list of meeting participants

Body:
I want to store a number of participants for a meeting. The order of them is not important. The only thing I want to make sure is, that I will be able to add and remove participants, use filter functions (and alike) and get their number. Also duplicates are not allowed.
I started using List for the method signature, but now I wonder if I should accept a more abstract type. I saw types like Traversable, TraversableLike, Iterable and IterableLike.

The number of participants will be rather low, usually below 100. Changes will be made occasionally. The participants are immutable (but they have mutable properties e.g. a List of actions they performed for that meeting).

What would be the appropriate abstraction level for my case?

Body:
You mentioned in your comments that your requirements include that:

A) You must be able to add and remove elements from the collection.

B) The order of the elements is not important.

C) Duplicate entries are not allowed.

I would suggest using an immutable Set. It should have effectively constant time additions, removals, and lookups, and will automatically prevent the addition of duplicates. This is probably a better fit than a List, which in Scala requires linear time to update, append to, or lookup in, as it is singly linked and can only be accessed starting from the head.

The syntax for adding and removing from an immutable set is fairly nice as well.

val xs = Set(alice, bob)
val xs2 = xs + carl              // Set(alice, bob, carl)
val xs3 = xs2 -- Set(alice, bob) // Set(carl)

You also get all your typical set operations, like unions, intersects, etc.

As with anything, if you have a large enough set of data that performance really matters, benchmark your results.

Reference: Performance Characteristcs of Scala Collections


问:
Explain MVC to non-programmers
I have a need to explain MVC to non-programmers.  Namely, to managers of other departments, in the context of progress report.  One of the things I do is refactor our codebase towards MVC separation.

What is MVC separation they might ask?
Why is it needed they might ask?

After reading a fairly technical answer like this:  What is MVC, really?, I am not entirely satisfied, since I will be talking to non-programmers.  They may nod their heads but they probably will not understand what it is and why it is needed.

In reality, I don't fully grasp what MVC is other than "separation of concerns, duties, functions, classes, blocks, tasks, things, in order to improve flexibility of making changes to the software".  Separating database from view and view from business logic using techniques like DI and OO tools and techniques is something I consider to be MVC separation.

So next time you are explaining MVC to a non-programmer who has background in sales and accounting for example, what would you tell them?

答:
Explain the advantages

I would explain MVC in terms of business benefits. Your managers will be able to understand this, and will get on board if the advantages are convincing.

MVC allows you to break down your application into sensible units, each of which exists independently of the others. You get clean, maintainable, testable code, and potentially code reuse between systems.

The Model

Each model encapsulates a single type of business information, for example, a customer record or a product, along with all related business logic.

Separating this out allows you to easily test your business logic in isolation from other parts of your application.

You can also easily extend the application by adding additional models, it's very modular and clean.

Each model in theory can exist independently of the others. You might consider enforcing this by using service objects to handle relationships between models. You can swap out models without affecting the rest of the system.

The View

Separating out your view allows you to easily update your front end without breaking the underlying back end.

You can give your front end code to another developer without necessarily giving them access to the whole system.

You are also free to create alternative front ends that work with the existing system. You might show your data as a mobile app, or an API, or a PDF, or an Excel spreadsheet. You can do this without hacking into the rest of the system. You're less likely to break things accidentally. You can readily create integration points for existing systems to hook into.

The Controller

The controller wires the models to the view. It keeps everything separate. You can wire in a different view very easily. If you change your model code, the view doesn't even need to know.

Other Advantages

It's a common pattern. Other developers will be able to understand your code and work on it. If you return to your code years later, you will likely be able to understand it and make changes. Your code will be less likely to become another legacy headache for a future developer.

Because everything has a place, it's much easier to produce clean code. The risk of spaghettification is dramatically reduced (though not eliminated). Your code becomes maintainable.

Because everything is modular, you can test parts of it in isolation. Your code is testable and less likely to harbour bugs or security holes. Future upgrades will be much easier as you will be able to easily test the whole system.

Title: Explain MVC to non-programmers


问:
create site with Codeigniter without database support
What approach could You suggest, If I don't have mysql or other database support on webhost, but I need to store data ( textual information ) for website somewhere. It's informative site for school - approx 20  to 50 visitors per day, 6 to 7 categories with 3 to 5 subcategories.
Would xml files be normal ?</p>

答:
I would recommend using the Jekyll Static Site Generator. It requires Ruby to be installed on your local development machine. It uses a simple template language that gets compiled down to static HTML files you can FTP to a web server. It's what GitHub uses when you host your own documentation sites for a Git repository.

Using something like CodeIgniter without a database feels like you are hitting a thumbtack with a sledge hammer, especially if you are the one doing all the updates.


问:
Why don't all UI Control methods RunOnUIThread
In both .NET and in Android and I'm sure other frameworks I've noticed this issue where you end up with a task that takes too long and so holds up the UI thread.

Say you have a method that updates a label with text from a network location/internet and comes back again after 3-4 seconds and sets the label appropriately.  That holds up the UI thread.
So your first port of call then is to move the method call to a different thread.
Only that doesn't just work... because you can no longer update the text of label since that can only be done in the UI thread....

So then the language provides something along the lines of

```<code>      runOnUiThread(() -> {
       label.setText(myNewFoundInformationFrom);
});
</code>```

That example is from Android using lambda's and is no doubt a massive improvement on what we might have used 10 years ago...

Maybe further down the line you find yourself doing this from various different places... so you might create a method

```<code>void setLabelText(string newText)
 runOnUiThread(() -> {
    label.setText(newText);
    });
</code>```

and at least in the case of Android... this works no matter which thread I run it from.

So this makes me wonder...  Why don't Microsoft/Google and all make it so that all update methods/functions to UI controls already make sure that they're running from the UI thread in this way - so that we don't have to?

答:
There are some concerns that may prevent such an always-runInUiThread approach.

The primary problem is that if you're in a non-UI thread, your operations are deferred by being posted onto a queue, so you have no idea of when your actions will actually take effect. If you have several changes that need to take effect at the same time, you need to group them in a lambda/function anyway and post it as usual, as otherwise another thread may manage to slip in a posted task between your tasks.

This has an analogue in resource synchronization, where it's incredibly common that you need to perform several operations under the same lock.

Synchronous functions are important, as you sometimes need to know that the result is locked in before continuing.


答:
I suppose the dangers are that people might become more concerned with playing the game than with actually making a worthwhile contribution to the site.  This is similar to what is happening in politics -- is it truly that the most qualified leaders are getting elected or that the people who are good at manipulating and playing the game getting elected?

It would be tougher to do on a technical site like Stack Overflow obviously -- where the answer is 1 or 0 (it works or it doesn't) -- but probably easier at a subjective opinion site like this.

Of course the benefits are that the people who do contribute feel like they are getting something in return -- even if they are really getting nothing back (like playing video games).

Title: What are your opinions on "Gamification"?

Body:
I watched an interesting Google Talk video (warning about an hour of your time) about Gamification of whatever you are doing.

It's clear that the StackExchange set of sites employ quite a few of these principles.  There's something compelling about making work fun, but I wonder how many problem domains can incorporate these ideas?  They definitely apply to social applications, but is that all?  The concept of a virtual loyalty program is also quite compelling.

Short description of Gamification:

There is a system of scoring and reward.  For example, Reputation in StackExchange is a type of scoring.  Badges are a type of reward.  The additional priviledges you gain as your reputation goes up are also a type of reward.

An example of a loyalty program with no real redemption would be a promotion that a convenience store did a while back where you buy their products and get FarmVille credits in return.  No real money or goods exchange hands, and the costs to the retailer are minimal at best.  Yet it brings in real money for these virtual paybacks.

Shameless use of JohnL's link: http://en.wikipedia.org/wiki/Gamification

NOTE:
The speaker refers to four classes of users which seem to have become the archetypes.  They are Achievers, Socializer, Explorer, and Killers.  The Achievers would most likely apply to all of us programmers--we like to get things done.  Apparently 80% of people are socializers and like light, non-confrontational interactions.  Explorers go to every corner of a game/application to discover whatever easter eggs and hidden features they can.  Killers not only want to win, they want you to lose and get praise/status for beating you.


问:
Should I create a single object for a common method call or use a throw away approach?
I'm creating a little rpg fight program just for fun and to practice my java (I'm pretty new hehe).

I have a class called Dice with a method called d20 that rolls a random number between 1 and 20. The method will be used frequently by all other classes in the program.

My question is, should I create a single instance of the Dice class in my main method that can be called by all the other classes too. Does that work? Does it need to be declared as a public reference variable to work? Is this just a poor practice?

Should I be making the method static instead so that I don't need to make an instance of the object at all?

Or should I create the object when the call is to be made and then throw it away afterwards using garbage collection?

I'm not sure the first way even works. The latter two I don't know which is good practice.

My main motivation here is to understand what the best practice is and why.

答:
When the method doesnt remember a state a static Mehtod should be okay.
java's shorthand random number method in the Math class (Math.random() ) is also a static method.


问:
Advice on structuring a Git repo into branches for an iterative tutorial
I'm a teacher and I'm about to publish a tutorial on how a build a PHP app in several iterative steps. At each iteration, I want to provide access to the associated source code and differences with the code of the previous iteration.

Naturally, I plan on using a Git repository for the project source code with a branch for each iteration. However, I wonder about future fixes and updates to my different branches. If I make a fix on a branch (say, iteration-03), I'd like it to "propagate" to all upcoming branches (iteration-04, iteration-05, and so on). My branches diffs must also stay coherent.

So my questions are :

What is be the best way to structure a Git repo into branches to achieve my goal ?

How to propagate fixes to a branch into the following ones ?

Thanks in advance for your answers.

Regards,
Baptiste

答:
Git is not a very suitable tool for this. In particular, git was created to keep track of the exact change history of data. While the branching system offers some support to keep different forks up to date, this is not very convenient. Let's assume you have the following history graph:

```<code>a1--a2  branch a
      \
       b1  branch b
         \
          c1--c2  branch c
</code>```

You now want to fix an error on branch a. We do this and commit the change as a3:

```<code>a1--a2--a3  branch a
      \
       b1  branch b
         \
          c1--c2  branch c
</code>```

To get the change to the other branches, we can either rebase each branch onto it's predecessor, which will replay the commits of each branch being rebased:

```<code>a1--a2--a3  branch a
          \
           b1'  branch b
              \
               c1'--c2'  branch c
</code>```

Or we could merge each branch into its successor (no fast-forwarding is possible so we'll get explicit merge commits b2 and c3):

```<code>a1--a2------a3  branch a
      \       \
       b1------b2  branch b
         \       \
          c1--c2--c3  branch c
</code>```

While rebasing makes the history look “nicer”, the merge commits tell us the real history of the project. In either case, any change will modify all dependent branches, and the history will clearly show the fix commit a3. Git does not automate keeping the dependent branches up to date, but you could write a script to assist you. Note that any merge or rebase may be interrupted if the changes cannot be resolved automatically, in which case you'll have to resolve manually.

Using this scheme, the diffs between the branches will stay fairly constant for changes in the base branch, since the change will be propagated to all dependent branches.

Alternative Strategy: Tags ✘

If you want to be able to fix previous ”versions“, then simply recording the history and tagging interesting states is not a viable option. We might start with a history like this:

```<code>a1--a2--b1--c1--c2  branch master
    ↑   ↑       ↑
tag a  tag b    tag c
</code>```

We could branch to create a fix branch where we commit the fix commit a3:

```<code>       a3  branch fix
      /
a1--a2--b1--c1--c2  branch master
    ↑   ↑       ↑
tag a  tag b    tag c
</code>```

We could then rebase the master branch onto fix:

```<code>       a3--b1'--c1'--c2' branch master
      /
a1--a2--b1--c1--c2
    ↑   ↑       ↑
tag a  tag b    tag c
</code>```

Unfortunately, the tags refer to their original commits and were not updated.

Alternative Strategy: Multiple folders with git remote ✔

Then, there's the possibility of simply storing each iteration in a separate directory. This is actually the most user-friendly option since it does not require git knowledge to access a specific state, but this makes it more difficult to properly track changes. One possibility to use git would be to have a separate git repository in each iteration folder. Each iteration would then mark the previous iteration's repository as the upstream repository. After each change, you would git pull the changes for each dependent repo.

While this is the most difficult to set up, this is likely to be the best and most intuitive solution for all participants.

Here is some code to set up an example project using this strategy:

```<code>#!/bin/sh

# create the three iterations a, b, c:
mkdir a b c

# fill each repository and set up upstream repos
cd a
git init
git commit --allow-empty -m 'a1'
git commit --allow-empty -m 'a2'

cd ../b
git clone --branch master ../a .
git commit --allow-empty -m 'b1'

cd ../c
git clone --branch master ../b .
git commit --allow-empty -m 'c1'
git commit --allow-empty -m 'c2'

cd ..
</code>```

Now we create a commit a3:

```<code>cd a
git commit --allow-empty -m 'a3'
cd ..
</code>```

To update the other repos, we simply issue a git pull:

```<code>cd b
git pull  # enter message for merge commit
cd ../c
git pull  # enter message for merge commit
cd ..
</code>```

After I ran those commands, the resulting log in c looked like

```<code>*   d8943fb c3
|\
| *   c670d4f b2
| |\
| | * f2ae31e a3
* | | e362453 c2
* | | 6e2a2d7 c1
|/ /
* | c78583c b1
|/
* 3c377e4 a2
* 098f321 a1
</code>```

This strategy ends up being functionally equivalent to propagating the changes via merging, but might be a bit easier to use – especially for newbies working through your tutorial if they downloaded the code as a zip archive. On the other hand, this makes it more difficult to distribute the complete tutorial as a git repo, since everything is distributed across multiple linked repos. If this is important, the equivalent ordinary merging described at the top is more likely to be better.

Body:
Git is not a very suitable tool for this. In particular, git was created to keep track of the exact change history of data. While the branching system offers some support to keep different forks up to date, this is not very convenient. Let's assume you have the following history graph:

a1--a2  branch a
      \
       b1  branch b
         \
          c1--c2  branch c

You now want to fix an error on branch a. We do this and commit the change as a3:

a1--a2--a3  branch a
      \
       b1  branch b
         \
          c1--c2  branch c

To get the change to the other branches, we can either rebase each branch onto it's predecessor, which will replay the commits of each branch being rebased:

a1--a2--a3  branch a
          \
           b1'  branch b
              \
               c1'--c2'  branch c

Or we could merge each branch into its successor (no fast-forwarding is possible so we'll get explicit merge commits b2 and c3):

a1--a2------a3  branch a
      \       \
       b1------b2  branch b
         \       \
          c1--c2--c3  branch c

While rebasing makes the history look “nicer”, the merge commits tell us the real history of the project. In either case, any change will modify all dependent branches, and the history will clearly show the fix commit a3. Git does not automate keeping the dependent branches up to date, but you could write a script to assist you. Note that any merge or rebase may be interrupted if the changes cannot be resolved automatically, in which case you'll have to resolve manually.

Using this scheme, the diffs between the branches will stay fairly constant for changes in the base branch, since the change will be propagated to all dependent branches.

Alternative Strategy: Tags ✘

If you want to be able to fix previous ”versions“, then simply recording the history and tagging interesting states is not a viable option. We might start with a history like this:

a1--a2--b1--c1--c2  branch master
    ↑   ↑       ↑
tag a  tag b    tag c

We could branch to create a fix branch where we commit the fix commit a3:

       a3  branch fix
      /
a1--a2--b1--c1--c2  branch master
    ↑   ↑       ↑
tag a  tag b    tag c

We could then rebase the master branch onto fix:

       a3--b1'--c1'--c2' branch master
      /
a1--a2--b1--c1--c2
    ↑   ↑       ↑
tag a  tag b    tag c

Unfortunately, the tags refer to their original commits and were not updated.

Alternative Strategy: Multiple folders with git remote ✔

Then, there's the possibility of simply storing each iteration in a separate directory. This is actually the most user-friendly option since it does not require git knowledge to access a specific state, but this makes it more difficult to properly track changes. One possibility to use git would be to have a separate git repository in each iteration folder. Each iteration would then mark the previous iteration's repository as the upstream repository. After each change, you would git pull the changes for each dependent repo.

While this is the most difficult to set up, this is likely to be the best and most intuitive solution for all participants.

Here is some code to set up an example project using this strategy:

#!/bin/sh

# create the three iterations a, b, c:
mkdir a b c

# fill each repository and set up upstream repos
cd a
git init
git commit --allow-empty -m 'a1'
git commit --allow-empty -m 'a2'

cd ../b
git clone --branch master ../a .
git commit --allow-empty -m 'b1'

cd ../c
git clone --branch master ../b .
git commit --allow-empty -m 'c1'
git commit --allow-empty -m 'c2'

cd ..

Now we create a commit a3:

cd a
git commit --allow-empty -m 'a3'
cd ..

To update the other repos, we simply issue a git pull:

cd b
git pull  # enter message for merge commit
cd ../c
git pull  # enter message for merge commit
cd ..

After I ran those commands, the resulting log in c looked like

*   d8943fb c3
|\
| *   c670d4f b2
| |\
| | * f2ae31e a3
* | | e362453 c2
* | | 6e2a2d7 c1
|/ /
* | c78583c b1
|/
* 3c377e4 a2
* 098f321 a1

This strategy ends up being functionally equivalent to propagating the changes via merging, but might be a bit easier to use – especially for newbies working through your tutorial if they downloaded the code as a zip archive. On the other hand, this makes it more difficult to distribute the complete tutorial as a git repo, since everything is distributed across multiple linked repos. If this is important, the equivalent ordinary merging described at the top is more likely to be better.


问:
Identifying user of a webapp
For a small webapp I want to be able to identify a user.

The issue is, if the user cheats in some manner, I want to be able
to forbid him the usage of my application.

I already have done extensive research on that topic, but to no avail.

What is not an option:

cookies: can be disabled or deleted (to easily overridable)

ip adress: is dynamic or hidden through NAT

MAC adress: cannot be retrieved (as far as I know, or at least not without terrifying the user)

Flash: is not supported on a wide range of devices

This is a central part, so I can decide which technology to use along
this decision.

What are the options I have? (especially I do not want that the user gets a security warning as this is often the case with java applets)

Some kind of unique machine identifier would be okay.

-edit-

What I want to protect against:

It should be some kind of discussion board about recent topics.
There will be people that proof that they have not the attitude to discuss in the public, e.g. insult other people etc.

And I want to have a possibility to keep these people away.

There will be somekind of login. But what keeps people from creating simply another account and keep going?

Fingerprinting seems to be to weak, as is has some well known flaws. Using a bank account is way to hard to use, at least since there is nothing you can buy right now, it will keep users from using the site.

Isn't there something in the middle? Like a device id, which keeps users from one device away, despite it might be wrong, this would do the job in a vast majority of cases I believe.

答:
Why don't you use phone verification? A user can't have 'n' no. of phones or at max of 2 or 3
When you ban a person, ban his phone no. too so that he can't verify again.

Simply use on-call/text user a code on his phone to enter into the browser.
This will not only help you identify the genuine users also help you keep spammers away.

Title: Identifying user of a webapp


答:
First, I would not call the class Dice. Rather call it DiceShaker or so and give it a method so you can call diceShaker.roll1W20() or even better, create different diceShakers (by composition/extending) for different purposes and make DiceShaker an interface.

Next, yes, it is good if you create a single instance that you pass to all the classes that need a DiceShaker. That way, you can easily test, if the DiceShaker works correct in unit tests. You can also give your classes special DiceShakers that can e.g. be more performant for edge cases.

E.g.:

```<code>public class Fighter {
    private DiceShaker diceShaker
    public Fighter(DiceShaker diceShaker) { this.diceShaker = diceShaker }
    public tryAttack(Fighter target) { if(diceShaker.roll1W20() > 10) this.attack(target) }
}
</code>```

(Note that the logic for attacking or not attacking should not be in the Fighter class as above. This is just to simplify this example.)

Don't make this static. It will then be hard to unit test your diceShaker or provide different functionality for different classes later on or at runtime. Same drawbacks are there if you create the DiceShaker the moment you need it and discard it after. This is the opposite of Dependency Injection.

Even though many java libs use static functions, most of the time that is not good practice or just a workaround for other flaws in the java language (like apache.commons.io.FileUtils)

Title: Should I create a single object for a common method call or use a throw away approach?

Body:
I'm creating a little rpg fight program just for fun and to practice my java (I'm pretty new hehe).

I have a class called Dice with a method called d20 that rolls a random number between 1 and 20. The method will be used frequently by all other classes in the program.

My question is, should I create a single instance of the Dice class in my main method that can be called by all the other classes too. Does that work? Does it need to be declared as a public reference variable to work? Is this just a poor practice?

Should I be making the method static instead so that I don't need to make an instance of the object at all?

Or should I create the object when the call is to be made and then throw it away afterwards using garbage collection?

I'm not sure the first way even works. The latter two I don't know which is good practice.

My main motivation here is to understand what the best practice is and why.

Body:
First, I would not call the class Dice. Rather call it DiceShaker or so and give it a method so you can call diceShaker.roll1W20() or even better, create different diceShakers (by composition/extending) for different purposes and make DiceShaker an interface.

Next, yes, it is good if you create a single instance that you pass to all the classes that need a DiceShaker. That way, you can easily test, if the DiceShaker works correct in unit tests. You can also give your classes special DiceShakers that can e.g. be more performant for edge cases.

E.g.:

public class Fighter {
    private DiceShaker diceShaker
    public Fighter(DiceShaker diceShaker) { this.diceShaker = diceShaker }
    public tryAttack(Fighter target) { if(diceShaker.roll1W20() > 10) this.attack(target) }
}

(Note that the logic for attacking or not attacking should not be in the Fighter class as above. This is just to simplify this example.)

Don't make this static. It will then be hard to unit test your diceShaker or provide different functionality for different classes later on or at runtime. Same drawbacks are there if you create the DiceShaker the moment you need it and discard it after. This is the opposite of Dependency Injection.

Even though many java libs use static functions, most of the time that is not good practice or just a workaround for other flaws in the java language (like apache.commons.io.FileUtils)