问:
Why is the "period of a (pseudo)random number generator" important?
I've been trying to understand (pseudo)random number generator code from various sources and the concept of the period continues to elude me.  To satisfy the minimum level of understanding, I've tried to think of it in terms of "sample size" from statistics.

However, I believe my understanding may be overly simplistic.  The documentation I've found for functions/calls that allow (or require) a period indicate the value is important but fall flat in explaining why...

Where it is possible for a programmer to set the period for a (pseudo)random number generator, what defines a good (optimal or desirable) period and why?

Additionally (for focused understanding):
 - Is it important (or helpful) to define the period using a prime number?
 - Does a large period or a small period produce a more desirable output?

答:
The other answers provide some good theory, but there is a piece of the practical application missing.

Where it is possible for a programmer to set the period for a
  (pseudo)random number generator

Generally, this cannot be set. This is a property of the generator function. Need a different period? Select a different function (or variation)

what defines a good (optimal or desirable) period and why?

Generally, a period should be as long as possible. A true RNG that uses real-world entropy has no period, and these are ideal for certain applications.

The longer the period, the less time before it repeats itself. If a PRNG repeats itself at the wrong moment, it could manifest as a user-visible anomaly (e.g. a card game dealing using the same deck order). Sometimes this is desirable: for example, one could give a Minecraft seed to someone else to check out the same generated world (technically nearly-same in the case of Minecraft, as the accepted answer points out). Sometimes, it is not: cryptographic applications are particularly sensitive to PRNGs that repeat, which is why they tend to include entropy as well.

PRNGs are necessarily bounded by the size of the variable used to hold its internal state: as the accepted answer says, the current state of the PRNG defines its next state. It is essentially a finite state automaton where you can (usually) pick your initial state (seed) and the states are one big loop. Using the pigeonhole principle one can prove that if the internal state is e.g. 32 bits, then the period of the PRNG has an upper bound of 232 unique states. Note that the actual period is likely to be lower: the state merely defines the theoretical upper bound.

In reality, it is possible, and increasingly more common, to increase the effective period or reduce the potential damage done when the period repeats by using these methods:

Use a larger internal state than is required by the user of the PRNG and return only part of the number. For example: if 32 bit integers are needed, use 64 bit state internally and simply return the lower 32 bits of each number. The same 32 bit integer may be returned multiple times. However the next number returned is unlikely to be the same because the actual internal state is different. For example:

Internal state: 0100 0110 returns 0110.

Internal state: 0011 0110 also returns 0110.

This is part of the strategy employed by the Mersenne Twister which has a famously long period (although it has certain drawbacks that should be considered).

Use multiple values to generate a single number. This is a strategy employed by some "real" entropy-based generators to "normalize" the data. For example: given a stream of binary digits, discard pairs that are different, and only use consecutive digits that match.

10 01 11 00 10 00 01 11 becomes 11 00 00 11 and like digits are combined, giving the quad 1001.

Depending on the data being extracted, this can alter the meaning of a value as it is reused as the period repeats, effectively making it something different. This is less useful for PRNGs than entropy-based RNGs, but it is still possible to treat the state as a bit stream. This can make the effective period larger depending on the strategy used and the data retrieved.

If the same value is treated differently when it repeats, it can mask the fact that the period repeated. This is similar to how Java's java.util.Random class works. If a value is retrieved as a 64 bit integer the first time and a 32 bit integer the next time, nobody might know it actually repeated. Examples of how to make this work assuming a 64 bit internal state:

If a 64 bit integer is requested, simply return the internal state.

If a shorter integer is requested, mask off some of the bits or combine them. Perhaps a 32-bit value could XOR both halves of the 64 bit value together.

If a boolean is requested, apply a technique to use all of the bits to determine the value (e.g. even number of bits set is false, odd is true).

Floating point values can be trickier due to IEEE 754 constraints on the bit pattern, but there are ways to use random bits to get random values.

If a bounded value (e.g. give me an integer from 1 to 100) is required, that makes the task even easier. A simple modulo operation can introduce bias, but one can apply techniques to use more of the bits to distribute the value evenly. The same state used twice but distributed against different intervals will likely return different numbers.

Include entropy when returning a value. Keep the same internal state, but maybe combine it with binary data representing something non-deterministic such as the internal temperature of the computer's CPU to many decimal places when returning a value from the PRNG. Maybe do the same thing but with the more precise internal clock that measures individual CPU ticks. This is on the edge of what a PRNG is, technically it is more of a hybrid approach, but similar tactics are used for seeding PRNGs in the first place.


问:
Workflow for chains of dependent pull requests to projects that depend on other projects
Suppose you have project A and project B, where project B depends on project A - let's say A is a library. And project A and project B live in separate version control repositories - either because project A was created by a third party, or because you just decided to organise your repositories that way. You want to make some changes to project B, but in order to do so you have to make some changes to project A. So you make two pull requests, one for your changes to project B and one for your changes to project A - these PRs "have to" be applied together - although in practice, of course, one of them has to be merged first (logically, it has to be the PR for project A) and here's where the problem can come in.

We have our CI server (TeamCity) set up to build all feature branches, so we can easily see if an individual, standalone PR to project B breaks things in project B. But because code in feature branches doesn't get published to our artifact repository (Nexus) until it's merged to master, this doesn't work so well for pairs (or even chains) of PRs like the scenario described above. We can only see, in a valid way, if the PR for project B is going to build on the build server after we've already merged the PR for project A. And it just so happened recently that this dependent build failed... because of a problem that only occurred on the build server.

Thus, we ended up with a situation where project B's master wasn't building due to a tightly-bound pair of PRs only being half-merged - the PR for project A had been merged, but the PR for project B hadn't been yet, due to the unexpected issue on the build server.

How could we adjust our workflow to avoid this kind of problem in future?

答:
Another option is to tie both (or any number of) projects together, side-by-side, to be managed in a monolithical manner:

no more worries about changeset dependencies, any combination of single or multi-repo changesets is supported, they're just like a regular changeset in a single repository

CI always works on all these tied-together repositories

no more waiting between teams working on different projects, everyone is on the same page

Effectively you're only dealing with a single project, not multiple inter-dependent ones.

See also this answer about how can this be achieved from the version control perspective: https://stackoverflow.com/a/30530140/4495081

ContentLicense: CC BY-SA 3.0


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: I spend a little bit of time each week just looking for new creative ways to do things that may or may not be directly related to what I'm currently working on.  Often I'll find new tricks or tools I was never aware of that speeds up my workflow.</p>

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

OwnerDisplayName: fscmj


问:
What is a good way to make estimates clear to the customer?
So me and my team have been doing estimates for a new project but we have been getting the feeling lately that the customer has trouble understanding not the estimates in itself but what the stories described actually contain.

We have been thinking of going through their RFP documentation and in this document make a connection to our excel list with estimations saying "this part is contained within this estimate". But this approach seems to me to be very time consuming and there has to be a better way to make sure that we cover what they expect us to cover in estimates while not making it too hard for them to understand.

My question: How would you approach a customer with estimates? In what format would this be? and foremost, how would you make sure the customer understands what you have estimated and what this story contains and thus rule out - for the most part - confusion between the two parties being my company and the customer's?

Edit: I do not think this is covered by the question proposed as duplicate since this question is more on presenting the estimates and omitting confusion between what is and what is not covered by it and the communication of this to the customer; while the duplicate presented is more of a way to have a client choose for agile and what to do if he does not, and the practices hereof.

Edit 2 on Comment of Thomas Owens:
The customer provides the requirements through a full text document describing their processes as best as they can and what it is that they want. Note that this might be large or complex things which we have then subdivided ourselves and written down in order to make a better estimate. The product owner is one of the customer's employees who is closest involved to the new application they want us to create but is not fully sure on all the details; leading to a lot of uncertainty on - for example - financial formulas and how they should be used.

What we have done is create a list in Excel with the processes (possible stories but not as such) described and trimmed down or split up to try having a better understanding on what each part contains; not so much technical but functional.

i.e.

Note this image is a trimmed down version for confidentiality reasons

答:
I think you've confused the customer with your internal teams.

The customer has given you a RFP and you've turned it into a set of user stories, assigned estimates to these and then gone back to the customer with your (internal) analysis. The customer has (quite rightly) looked at these and said "what's this got to do with what we originally asked for?"

As far as the customer is concerned, what you do and how you do it is entirely up to you. What they want to know is how much of their request they will get and how long it will costs them (or how long it'll take), so you have to communicate with the customer in their terms.

So when you turned their RFP into stories, you should already have been tracking which story corresponded to which part of the RFP. Then it should be an easy matter to roll the story estimates up and put them back into the RFP. If you didn't do this, then you'll have to take the hit now (which has a benefit of checking you have covered every part of their RFP,how else do you know if you've not missed something)

eg,. if the customer asked you to "make a widget", and you turned that into 3 user stories of "cast widget", "polish widget", and "box widget", you can add those 3 story estimates together to give the customer the answer they're looking for.


答:
Try checking your emails with longer intervals and stop using online social tools like Twitter, facebook etc.

Use this wallpaper.

Try to work with open front view. I usually use conference room when its free, it helps me focus!

Try to work with other programers around you.

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: Adnan Memon


问:
What is the conceptual difference between finally and a destructor?
First, I am well aware of Why is there no 'finally' construct in C++? but a lengthy-growing comment discussion on another question seems to warrant a separate question.

Apart from the issue that finally in C# and Java can basically exist only once (== 1) per scope and a single scope can have multiple (== n) C++ destructors, I think that they are essentially the same thing. (With some technical differences.)

However, another user argued:

... I was trying to say that a dtor is inherently a tool for (Release sematics) and
finally is inherently a tool for (Commit semantics). If you don't see why: consider
why it's legitimate to throw exceptions on top of each other in
finally blocks, and why the same is not for destructors. (In some
sense, it's a data vs. control thing. Destructors are for releasing
data, finally is for releasing control. They are different; it's
unfortunate that C++ ties them together.)

Can someone clear this up?

答:
Glad you posted this as a question. :)

I was trying to say that destructors and finally are conceptually different:

Destructors are for releasing resources (data)

finally is for returning to the caller (control)

Consider, say, this hypothetical pseudo-code:

try {
    bar();
} finally {
    logfile.print("bar has exited...");
}
```

<p><code>finally</code> here is solving entirely a control problem and not a resource management problem.<br>
It wouldn't make sense to do that in a destructor for a variety of reasons:</p>

<ul>
<li>No <em>thing</em> is being "acquired" or "created"</li>
<li>Failure to print to the log file will <em>not</em> result in resource leaks, data corruption, etc. (assuming that the logfile here is not fed back into the program elsewhere)</li>
<li>It is legitimate for <code>logfile.print</code> to fail, whereas <em>destruction</em> (conceptually) <em>cannot fail</em></li>
</ul>

<p>Here's another example, this time like in Javascript:</p>

<pre class="lang-d prettyprint-override"><code>var mo_document = document, mo;
function observe(mutations) {
    mo.disconnect();  // stop observing changes to prevent re-entrance
    try {
        /* modify stuff */
    } finally {
        mo.observe(mo_document);  // continue observing (conceptually, this can fail)
    }
}
mo = new MutationObserver(observe);
return observe();
</code>```

In the above example, again, there are no resources to be released.

In fact, the finally block is acquiring resources internally to achieve its goal, which could potentially fail. Hence, it doesn't make sense to use a destructor (if Javascript had one).

On the other hand, in this example:

b = get_data();
try {
    a.write(b);
} finally {
    free(b);
}
```

finally is destroying a resource, b. It's a data problem. The problem is not about cleanly returning control to the caller, but rather about avoiding resource leaks.

Failure is not an option, and should (conceptually) never occur.

Every release of b is necessarily paired with an acquisition, and it makes sense to use RAII.

In other words, just because you can use either to simulate either that doesn't mean both are one and the same problem or that both are appropriate solutions for both problems.

Body:
Glad you posted this as a question. :)

I was trying to say that destructors and finally are conceptually different:

Destructors are for releasing resources (data)

finally is for returning to the caller (control)

Consider, say, this hypothetical pseudo-code:

try {
    bar();
} finally {
    logfile.print("bar has exited...");
}

finally here is solving entirely a control problem and not a resource management problem.

It wouldn't make sense to do that in a destructor for a variety of reasons:

No thing is being "acquired" or "created"

Failure to print to the log file will not result in resource leaks, data corruption, etc. (assuming that the logfile here is not fed back into the program elsewhere)

It is legitimate for logfile.print to fail, whereas destruction (conceptually) cannot fail

Here's another example, this time like in Javascript:

var mo_document = document, mo;
function observe(mutations) {
    mo.disconnect();  // stop observing changes to prevent re-entrance
    try {
        /* modify stuff */
    } finally {
        mo.observe(mo_document);  // continue observing (conceptually, this can fail)
    }
}
mo = new MutationObserver(observe);
return observe();

In the above example, again, there are no resources to be released.

In fact, the finally block is acquiring resources internally to achieve its goal, which could potentially fail. Hence, it doesn't make sense to use a destructor (if Javascript had one).

On the other hand, in this example:

b = get_data();
try {
    a.write(b);
} finally {
    free(b);
}

finally is destroying a resource, b. It's a data problem. The problem is not about cleanly returning control to the caller, but rather about avoiding resource leaks.

Failure is not an option, and should (conceptually) never occur.

Every release of b is necessarily paired with an acquisition, and it makes sense to use RAII.

In other words, just because you can use either to simulate either that doesn't mean both are one and the same problem or that both are appropriate solutions for both problems.


问:
Is it practical to abandon STL in C++ development?
I know in some areas (game industry, for example), STL is not recommended.
So my question is: is it really a good practice not to use STL in some cases? If so, what's the biggest reasons of not using the modern C++'s STL?</p>

答:
I'm using STL and boost for many years already. If I wanted to abandon it and use my custom tools, the motivation would be:

Compile time reduction (75%). Just including iostreams can add 1 million lines of code to your module. Yes precompiled headers help a lot, but it still slows down the compilation a lot in big projects. In the long run, it wastes a lot of time of anyone working on it.

Performance. (25%) STL is written to work generally, but you can optimise your structures to work exactly as you want. For example, you might have a data structures with millions of short strings. It might be much faster to use custom string class based on the principal of boost::small_vector (small static local vector of data, dynamic allocation only for larger strings), these kind of changes can make critical sections of code work many times faster.


问:
Enforce uniqueness of personal contact records in a system or not?
I have a contact table which stores all the contact information of a person such as name, address, phone number.

The system would be more user friendly if it can prevent users from accidentally entering duplicate records.

If it is unique it will be more user friendly, but it costs performance to check, plus the added code increases the maintenance cost in the future.

If it's not necessary from a business requirement standpoint, have you found person/contact records to be worth maintaining uniqueness in? Can you think of any problems I might run into enforcing uniqueness on them?

答:
Possibly, but if these contact records are going to be entered by employees, it is perfectly possible that you could have a difference in address/name/phone number styles that would make this difficult. E.g. for address:

```<code>1 High Street
1, High Street
1 High St
</code>```

This applies across columns too:

```<code>Joe Smith|1 High Street
Jo Smith|1 High St
</code>```

I'd also consider storing phone numbers (perhaps even addresses) in a separate table from the contact since a contact can have more than one number.

Your interface can assist greatly here too (assuming you have one). Address lines, names and phone numbers can be broken up into their constituent parts and validated.

Body:
Possibly, but if these contact records are going to be entered by employees, it is perfectly possible that you could have a difference in address/name/phone number styles that would make this difficult. E.g. for address:

1 High Street
1, High Street
1 High St

This applies across columns too:

Joe Smith|1 High Street
Jo Smith|1 High St

I'd also consider storing phone numbers (perhaps even addresses) in a separate table from the contact since a contact can have more than one number.

Your interface can assist greatly here too (assuming you have one). Address lines, names and phone numbers can be broken up into their constituent parts and validated.


问:
Workflow, editing things not in your current task
Usually when I program, I have a clear task ahead of me, but find annoying things I'd like to clean up as I go on.

Here I see three options:

Do it later (may forgot/have to spend time adding a ticket)

Do it now and commit it together with my current work (unclear)

Do it now and the commit it separately (have to find it, might make a mistake and go for option #2 unintentionally)

This is probably fairly basic, but what are some ways to circumvent this using svn/git/other?

答:
Personally, I think it depends :-).

For small fixes, option three (now, in a seperate commit) is best, because the overhead of doing it later is not worth it. In that case, you just create a separate commit. How to do that depends on the VCS you use, and is a separate question :-).

If it is a larger fix, you create a ticket. Otherwise, you risk constantly getting derailed from your main task ("Oh, look, another opportunity for refactoring, oh, there's another, and there, and there...").


答:
Forgive me, but I think you've rather put the cart before the horse. Whenever I've dealt with a RFP/ITT etc, the client is really looking for a high-level idea of your approach to the problem. This happens for a number of reasons:

So they can be comfortable that you understand the requirements such
as they are

You can demonstrate the technical nous required to
deliver

You've managed to read between the lines and cater for any
    pitfalls endemic in the functional area at hand

Can pitch all of the
    above at a sufficient level

The breaking down of the requirements into tasks comes after this process has been completed.

Title: What is a good way to make estimates clear to the customer?

Body:
So me and my team have been doing estimates for a new project but we have been getting the feeling lately that the customer has trouble understanding not the estimates in itself but what the stories described actually contain.

We have been thinking of going through their RFP documentation and in this document make a connection to our excel list with estimations saying "this part is contained within this estimate". But this approach seems to me to be very time consuming and there has to be a better way to make sure that we cover what they expect us to cover in estimates while not making it too hard for them to understand.

My question: How would you approach a customer with estimates? In what format would this be? and foremost, how would you make sure the customer understands what you have estimated and what this story contains and thus rule out - for the most part - confusion between the two parties being my company and the customer's?

Edit: I do not think this is covered by the question proposed as duplicate since this question is more on presenting the estimates and omitting confusion between what is and what is not covered by it and the communication of this to the customer; while the duplicate presented is more of a way to have a client choose for agile and what to do if he does not, and the practices hereof.

Edit 2 on Comment of Thomas Owens:
The customer provides the requirements through a full text document describing their processes as best as they can and what it is that they want. Note that this might be large or complex things which we have then subdivided ourselves and written down in order to make a better estimate. The product owner is one of the customer's employees who is closest involved to the new application they want us to create but is not fully sure on all the details; leading to a lot of uncertainty on - for example - financial formulas and how they should be used.

What we have done is create a list in Excel with the processes (possible stories but not as such) described and trimmed down or split up to try having a better understanding on what each part contains; not so much technical but functional.

i.e.

Note this image is a trimmed down version for confidentiality reasons


答:
In a way they are - in the same way that a Ferrari and a transit can both be used to nip down the shops for a pint of milk even though they're designed for different uses.

You could place a try/finally construct in every scope and clean up all scope defined variables in the finally block to emulate a C++ destructor. This is, conceptually, what C++ does - the compiler automatically calls the destructor when a variable goes out of scope (ie at the end of the scope block). You'd have to arrange your try/finally so the try is the very first thing and the finally the very last thing in each scope however. You'd also have to define a standard for each object to have a specifically-named method that it uses to clean up its state that you would call in the finally block, though I guess you could leave the normal memory management your language provides to clean up the now-emptied object when it likes.

It wouldn't be pretty to do this though, and even though .NET introduced IDispose as a manually managed destructor, and using blocks as an attempt to make that manual management slightly easier, its still not something you'd want to do in practice.

Title: What is the conceptual difference between finally and a destructor?

Body:
First, I am well aware of Why is there no 'finally' construct in C++? but a lengthy-growing comment discussion on another question seems to warrant a separate question.

Apart from the issue that finally in C# and Java can basically exist only once (== 1) per scope and a single scope can have multiple (== n) C++ destructors, I think that they are essentially the same thing. (With some technical differences.)

However, another user argued:

... I was trying to say that a dtor is inherently a tool for (Release sematics) and
finally is inherently a tool for (Commit semantics). If you don't see why: consider
why it's legitimate to throw exceptions on top of each other in
finally blocks, and why the same is not for destructors. (In some
sense, it's a data vs. control thing. Destructors are for releasing
data, finally is for releasing control. They are different; it's
unfortunate that C++ ties them together.)

Can someone clear this up?


问:
Is it ok to use service locator for ubiquitously used dependencies?
We strictly adhere to inversion of control in our codebase, but that creates hellish constructors (yes, I know that means our classes aren't cohesive enough, this is a work in progress).
The thing is, that sometimes those dependencies are quite silly like a DateTime wrapper to enable date mocking, or the logger, or a TaskFactory wrapper which are not directly related to the business of the class and I do not think they require explicit introduction.

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system? What would be the disadvantages?

答:
Dependency injection solves a particular problem, however as you're finding it adds complexity.  It's not something you should always do for everything because its 'always good', as it can actually add overhead for certain kinds of maintenance.  For instance a change where you add a requirement to use a dependency in a method requires your code to change to both add an injection field to the constructor and the change where you use the dependency itself.

Dependency injection allows you to change this later.  For something such as a date, if you do not envisage in any situation that your date-handling system will change (which is pretty much the case for any mature programming language which provides date handling), adding dependency injection for this function has a cost and gives you nothing.  So don't do it.  If you do you are violating the principle of You Ain't Gonna Need It.

So if you don't need the flexibility DI gives you for some of the services you're DIing, just take them out, use a service locator or even (horror) a direct dependency.  Its a judgement: if you later find you actually do need that flexibility, modern code dev platforms will let you add it in without too much pain.


答:
Pretty much all the answers have been said to death in numerous places here and elsewhere. Or, at least I've heard it to death. Learn your IDE, learn to type faster, use frameworks, use code generation, etc., etc. Yes of course these things will help and I doubt there are many programmers who are masters of them all. But being the type of programmer that asks these questions and frequents sites like Stack Overflow you knew these things already. Did you merely want to here them repeated or did you just want to vent a little?

But what if we were able to get to that state? I mean master all these suggestions? What would happen then? Well. I'd guess that time-lines will be reduced even further. And again, we'll revert to a perception of quality. I mean, our craft has definitely progressed and become more and more productive over the decades. But has quality increased during this time (excluding the very early years of course)?

My answer is simple: quality software takes time! You can only trade one for the other (quality/speed). But yes we all know that however we're not honest about the degree to which that trade-off often ends up on the speed end of the scale. And we are even greater liars early on in projects!

I say that you are not at fault here. The problem is the perception people have of how long quality software should take. We fool ourselves in believing we are capable of creating quality software with the types of time-lines our managers or even we guesstimate. We do not make quality software. We write software that works but sometimes with flashes of quality in certain corners of an application.

So what can we do about this? We can't just convince our bosses that we need to double or triple the investment in each of our projects. I say lead by example. Create a truly great piece of software as a side project. Put your own time into it and do not compromise. All the while pay attention to how you progress. Make note of the apparently unrelated tasks you've had to put an unexpected amount of time in and see if you can justify it. Contrast this with all the other projects you've worked. Be brutally honest with yourself and all aspects of this analysis. Can the extra things you did with your quality software be neglected in "real" projects at work? But maybe your attempt failed. What was the reason? Did you get bored and just rushed to get the core features done? I've yet to do something like this myself which is why I end off this thought with some doubt - but I intend to give it a real go. I'll keep you posted :).

Finally, I think most (if not all) performance evaluations are twisted and extraordinarily manipulative. You can't throttle quality and speed at 100%. Your boss should be scoring you against a standard that is set by the organization. The organization's standard on the trade-off between quality and speed. Lets imagine that OrangeSoft Inc. expects 33% quality and 66% speed. So if you're writing code that has maybe a third of the unit tests it should but making it up with speed and reduced delivery time you should score near 100% on your review! (These are pretty rough analogies but you get the point). But instead, what happens is that Bob writes code extremely fast but which is notoriously buggy. So on his performance review he'll score 3/5 for quality and 5/5 for speed. Carol on the other hand writes code much slower but produces significantly less bugs. She scores 5/5 for quality but 3/5 for speed. Either way Bob and Carol get docked on their raise. Is it possible for any employee to get a perfect score? Is this fair?

Title: How to become a "faster" programmer?

OwnerDisplayName: Thiru


答:
From my point of view the main difference is that a destructor in c++ is an implicit
mechanism (automatically invoked) for releasing allocated resources
while the try ... finally can be used as an explicit mechanism to do that.

In c++ programmes the programmer is responsible for releasing allocated resources.
This is usually implemented in the destructor of a class and done immediately when a
variable goes out of scope or
or when delete is called.

When in c++ a local variable of a class is created without using new the resources
of that instances are freed implicit by the destructor when there is an exception.

```<code>// c++
void test() {
    MyClass myClass(someParameter);
    // if there is an exception the destructor of MyClass is called automatically
    // this does not work with
    // MyClass* pMyClass = new MyClass(someParameter);

} // on test() exit the destructor of myClass is implicitly called
</code>```

In java, c# and other systems with an automatic memory management
the systems garbage collector decides when a class instance is destroyed.

```<code>// c#
void test() {
    MyClass myClass = new MyClass(someParameter);
    // if there is an exception myClass is NOT destroyed so there may be memory/resource leakes

    myClass.destroy(); // this is never called
}
</code>```

There is no implicit mechanism to that so you have to program this explicitly using try finally

```<code>// c#
void test() {
    MyClass myClass = null;

    try {
        myClass = new MyClass(someParameter);
        ...
    } finally {
        // explicit memory management
        // even if there is an exception myClass resources are freed
        myClass.destroy();
    }

    myClass.destroy(); // this is never called
}
</code>```

Body:
From my point of view the main difference is that a destructor in c++ is an implicit
mechanism (automatically invoked) for releasing allocated resources
while the try ... finally can be used as an explicit mechanism to do that.

In c++ programmes the programmer is responsible for releasing allocated resources.
This is usually implemented in the destructor of a class and done immediately when a
variable goes out of scope or
or when delete is called.

When in c++ a local variable of a class is created without using new the resources
of that instances are freed implicit by the destructor when there is an exception.

// c++
void test() {
    MyClass myClass(someParameter);
    // if there is an exception the destructor of MyClass is called automatically
    // this does not work with
    // MyClass* pMyClass = new MyClass(someParameter);

} // on test() exit the destructor of myClass is implicitly called

In java, c# and other systems with an automatic memory management
the systems garbage collector decides when a class instance is destroyed.

// c#
void test() {
    MyClass myClass = new MyClass(someParameter);
    // if there is an exception myClass is NOT destroyed so there may be memory/resource leakes

    myClass.destroy(); // this is never called
}

There is no implicit mechanism to that so you have to program this explicitly using try finally

// c#
void test() {
    MyClass myClass = null;

    try {
        myClass = new MyClass(someParameter);
        ...
    } finally {
        // explicit memory management
        // even if there is an exception myClass resources are freed
        myClass.destroy();
    }

    myClass.destroy(); // this is never called
}


问:
One C codebase as an standalone application as well as Fast-CGI and Apache module
I'm familiar with C, but haven't written any medium or large application in it. I have a requirement to built an application that can be run as a standalone console application as well as Fast-CGI and Apache module.

I'm thinking of implementing the core functionality as a Static Library and then write a wrapper for console, Fast-CGI and Apache module.

As I'm not a C expert, I was wondering what are my other options. Having the core functionality in a standalone binary and calling it using system calls from the wrappers would work also, however I can't fully write down the pros and cons of each.

Also the software is supposed to run on GNU/Linux machines, so I'm very open to follow the community conventions.

答: Why dont you write the core functionality as a dynamic link library in a sdk fashion with clear defined Interface for all the other components so you dont have to link the lib to each need ex. Console application etc.</p>


答:
Q:What do you do to get more done in
  shorter time periods?

A: Everyday come to office and write what all you would want to finish on that in (sticky notes) outlook notes. Start working on that order of the items. Believe me at the end of the day you would feel you have done what you had planned and thats a great feeling.

Title: How to become a "faster" programmer?

OwnerDisplayName: Cshah


问:
Possible way to make java class builder more abstract by using interface required keys
I'm looking for a more abstract pattern for builders that handles required
fields without the need of writing a validator that checks if all requried fields are set.

I like this builder. But is there a way to make the interfaces more abstract
so that I don't need to create a new interface for each required field?

```<code>public class Example {

    private String first;
    private String second;
    private String third;
    private String fourth;
    private String fifth;

    public static RequiredSecond builder(String first) {
        return new ExampleBuilder(first);
    }

    public interface RequiredSecond {
        RequiredThird withSecond(String second);
    }

    public interface RequiredThird {
        RequiredFourth withThird(String third);
    }

    public interface RequiredFourth {
        Build withFourth(String fourth);
    }

    public interface Build {
        Build withFifth(String fifth);

        Example build();
    }

    private static class ExampleBuilder implements RequiredSecond, RequiredThird, RequiredFourth, Build {
        Example example = new Example();

        public ExampleBuilder(String first) {
            example.setFirst(first);
        }

        @Override
        public Build withFifth(String fifth) {
            example.setFifth(fifth);
            return this;
        }

        @Override
        public Example build() {
            return example;
        }

        @Override
        public Build withFourth(String fourth) {
            example.setFourth(fourth);
            return this;
        }

        @Override
        public RequiredFourth withThird(String third) {
            example.setThird(third);
            return this;
        }

        @Override
        public RequiredThird withSecond(String second) {
            example.setSecond(second);
            return this;
        }
    }

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getSecond() {
        return second;
    }

    public void setSecond(String second) {
        this.second = second;
    }

    public String getThird() {
        return third;
    }

    public void setThird(String third) {
        this.third = third;
    }

    public String getFourth() {
        return fourth;
    }

    public void setFourth(String fourth) {
        this.fourth = fourth;
    }

    public String getFifth() {
        return fifth;
    }

    public void setFifth(String fifth) {
        this.fifth = fifth;
    }

    @Override
    public String toString() {
        return "Example [first=" + first + ", second=" + second + ", third=" + third + ", fourth=" + fourth +
                ", fifth=" + fifth + "]";
    }

}
public class Labb {

    public static void main(String[] args) {
        // All required including optional
        Example ex1 = Example.builder("first").withSecond("second").withThird("third").withFourth("fourth").withFifth("optional fith").build();
        System.out.println(ex1);
        // Output: Example [first=first, second=second, third=third, fourth=fourth, fifth=optional fith]

        // All required excluding optional
        Example ex2 = Example.builder("first").withSecond("second").withThird("third").withFourth("fourth").build();
        System.out.println(ex2);
        // Output: Example [first=first, second=second, third=third, fourth=fourth, fifth=null]
    }
}
</code>```

答:
With your design, the programmer must call all yours methods in the order you define. In this case, if you have only a few parameters, a constructor should be perfect.

What I prefer in the builder pattern is that you can call the methods in the order the developer want.

The build method should validate the required values.

```<code>public class Builder {
    private String first;
    ...

    public Builder first(String first) {
        this.first = first;
        return this;
    }

    public Example build() {
        if(first == null) throw new IllegalArgumentException("first can't be null");
        return new Example(this.first);
    }
</code>```

Body:
With your design, the programmer must call all yours methods in the order you define. In this case, if you have only a few parameters, a constructor should be perfect.

What I prefer in the builder pattern is that you can call the methods in the order the developer want.

The build method should validate the required values.

public class Builder {
    private String first;
    ...

    public Builder first(String first) {
        this.first = first;
        return this;
    }

    public Example build() {
        if(first == null) throw new IllegalArgumentException("first can't be null");
        return new Example(this.first);
    }


问:
Implementing per-user storage usage quota in SaaS products
In a SaaS solution, that allows users to maintain their data on the server, if I have to implement various pricing schemes, where each scheme offers different storage quota, say, Basic subscription gets you 2GB storage, whereas Premium gets you 10GB storage - what kind of architecture one has to use?

Do I need to maintain against user profile the quota being used?

Will this work only if data is maintained in file system?  What happens if data is stored in relational or NoSQL database - how one keeps track of user-level usage of storage in such cases?

答:
The academic approach would be to have a discrete, as brief as possible, but complete layer between application and persistence medium (whether it be filesystem, database, or a combination thereof) which counts the size of everything that is added, modified, or removed from persistence and keeps updating the total in the profile.

However, at some point in time you will inevitably run into the problem of having to recalculate everything, so since you will most probably have to write the recalculate-everything code, you might wish (at least in the beginning) to reuse that code and skip the academic solution.  So, each time there is an insertion, update or removal, you set a "dirty" flag in the profile, and then you have a separate batch process which looks for "dirty" profiles and recalculates the amount of space occupied, by querying the filesystem, the database, etc.

Of course, this means that quota changes will not be visible immediately, and most importantly, once you have enough customers this approach will be too expensive to be viable, but once you have enough customers you will presumably be rich enough to be able to afford a complete rewrite.

Or, go with the academic solution.


答:
The reason for using a dll is to ship changes to that dll only, the interface wrappers will be unchanged. YMMV if you ship all 3 components simultaneously, so building a static lib and shipping everything each time the code gets an update isn't a bad idea in that case.

You could also consider embedding a webserver (like mongoose or civetweb) in your application so the user can just start it up and get full web functionality without needing apache or fastcgi at all.

Title: One C codebase as an standalone application as well as Fast-CGI and Apache module

Body:
I'm familiar with C, but haven't written any medium or large application in it. I have a requirement to built an application that can be run as a standalone console application as well as Fast-CGI and Apache module.

I'm thinking of implementing the core functionality as a Static Library and then write a wrapper for console, Fast-CGI and Apache module.

As I'm not a C expert, I was wondering what are my other options. Having the core functionality in a standalone binary and calling it using system calls from the wrappers would work also, however I can't fully write down the pros and cons of each.

Also the software is supposed to run on GNU/Linux machines, so I'm very open to follow the community conventions.


答:
Pair program -- this has all sorts of benefits:

forces you to articulate/clarify your thinking

gives you insight into how someone else works, many ideas which you can adopt/try

learn new technologies directly from someone else who knows them

pick up little productivity tips from others. You always see someone use a menu command you didn't understand before, or some useful Unix command.

Title: How to become a "faster" programmer?

OwnerDisplayName: ndp


答:
Add a size field to each thing that is stored.  This field could be approximate, but it should be updated to reflect the new size whenever the item is modified.

Add a space_used field on the User. Whenever something with a size is added or modified, run a query for all the items the user owns, sum the size fields, and update the space_used field on the user.  If you aren't using a relational database, you could try little efficiency tricks like just adding or subtracting the size change of the item they just modified, but this will fail if there is any possible way that a user could modify 2 items at once.

Either on the User, or on the Company (depending on who is paying for the licenses) you need to store the space_quota to compare against.

The result:

You'll have to check User.space_used < space_quota before allowing the user to add any items or increase the size of any items, so space_used needs to be pre-calculated to keep the query fast.  You need Item.size to later answer the question, "How did we calculate User.space_used because it looks wrong?"

Using such a system, it should be easy to give the user warning when they reach 80% or 95% of their quota.

Title: Implementing per-user storage usage quota in SaaS products

Body:
In a SaaS solution, that allows users to maintain their data on the server, if I have to implement various pricing schemes, where each scheme offers different storage quota, say, Basic subscription gets you 2GB storage, whereas Premium gets you 10GB storage - what kind of architecture one has to use?

Do I need to maintain against user profile the quota being used?

Will this work only if data is maintained in file system?  What happens if data is stored in relational or NoSQL database - how one keeps track of user-level usage of storage in such cases?


问:
Use verbs with functions, nouns with classes - what about interfaces?
Ok, I understand the normal conventions of using verbs with functions and nouns with classes. What about interfaces? Is there any methodology when coming up with interface names that may not be that obvious?

Just to make it clear, I'm not talking about whether to put an "I" in front of the name or if to use camelCase or PascalCase. I'm wondering about the method of figuring out a clear, semantic name for an interface.

EDIT
I'm obsessing on how to name an interface in the clearest way. I guess it just needs to be a noun too because when I think of naming classes I think of the closest "real" world object it can relate to. I suppose real world interfaces are things like a keyboard, mouse, remote control, ATM screen. Those are all nouns. Anyhow, any additional insight on a good way to formulate interface names would be appreciated.

答: It depends, if the interface contains only methods it will be good to name it using a verbs like "Actions" where as if it represents a generic class wchich contains static , final fields then we can use a generic Noun just like "Vehicle"</p>


问:
Is there particular circumstance that throwing root superclass exceptions is a good practice?
I've been taught that exceptions should be have concise meanings and should contain a message that explains to the client what the exceptional situation is. I am wondering, since I found a piece of code that contains a couple of lines into a try catch block and in the end catches a generic exception with the message: An error occurred performing the task

This is written in a library and somehow I trigger this exception. How am I supposed to fix what is broken if I do not know what is broken? Generally I know that this is not a good practice. Are there any situations that throwing/catching generic exceptions is a good practice?

答:
a couple of lines into a try catch block and in the end catches a
  generic exception with the message: An error occurred performing the
  task

Do you mean something like:

```<code>try {
    thingWhichThrowsDescriptiveException();
} catch (Throwable t) {
    throw new Exception("An error occurred");
}
</code>```

If so, then my answer is No.  You are entitled to whatever righteous indignation you feel when you see this.  It just throws away the details of the exception and replaces them with garbage.

If you don't want an exception in your method signature, do this instead: Workaround for Java checked exceptions

Body:
a couple of lines into a try catch block and in the end catches a
  generic exception with the message: An error occurred performing the
  task

Do you mean something like:

try {
    thingWhichThrowsDescriptiveException();
} catch (Throwable t) {
    throw new Exception("An error occurred");
}

If so, then my answer is No.  You are entitled to whatever righteous indignation you feel when you see this.  It just throws away the details of the exception and replaces them with garbage.

If you don't want an exception in your method signature, do this instead: Workaround for Java checked exceptions


问:
Reading from Memory vs Performing an Operation
I'm learning to program microcontrollers and am trying to develop good habits:

Suppose I have a set of values which can be calculated based on what is already in memory.  As a general rule, is it always better to calculate the data once, and save it in memory, or is it always better to calculate it each time it's needed?

My guess would be that since reading and writing to memory is slower than processor operations, it would always be better to calculate something each time it's needed rather than storing the value in memory, provided the calculation is somewhat trivial.

Am I correct in my thinking?

答:
Suppose I have a set of values which can be calculated based on what
  is already in memory.

What's faster - reading from memory, or reading from memory and performing a calculation?

What you're thinking of is true, some calculations are quicker than a memory read and so, if you're concerned about your CPU cache hits or memory usage, re-calculating may well be a good thing, but in the general case, caching is never a bad choice. Even when you save no time, you at least have implemented a mechanism that can be used later on when you do have a complex value that requires caching.

The only time you really want to avoid caching is when you're controlling what memory gets loaded into the CPU. Having to chuck all that out to load a block of memory just so you can read a value, and then refill the cache with the original memory can be very expensive (relatively speaking). 99% of programs don't do this though, reading memory is one of those things they do all the time so a cache makes no difference to execution time. YMMV if you're writing for a microcontroller with very limited memory.


问:
Workaround for Java checked exceptions
I appreciate a lot the new Java 8 features about lambdas and default methods interfaces. Yet, I still get bored with checked exceptions. For instance, if I just want to list all the visible fields of an object I would like to simply write this:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
        f -> System.out.println(f.get(p))
    );
</code>```

Yet, since the get method might throw a checked exception, which does not agrees with the Consumer interface contract, then I must catch that exception and write the following code:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            f -> {
                try {
                    System.out.println(f.get(p));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
    );
</code>```

However in most cases I just want the exception to be thrown as a RuntimeException and let the program handle, or not, the exception without compilation errors.

So, I would like to have your opinion about my controversial workaround for checked exceptions annoyance. To that end, I created an auxiliary interface ConsumerCheckException<T> and an utility function rethrow (updated according to the sugestion of Doval's comment) as follows:

```<code>  @FunctionalInterface
  public interface ConsumerCheckException<T>{
      void accept(T elem) throws Exception;
  }

  public class Wrappers {
      public static <T> Consumer<T> rethrow(ConsumerCheckException<T> c) {
        return elem -> {
          try {
            c.accept(elem);
          } catch (Exception ex) {
            /**
             * within sneakyThrow() we cast to the parameterized type T.
             * In this case that type is RuntimeException.
             * At runtime, however, the generic types have been erased, so
             * that there is no T type anymore to cast to, so the cast
             * disappears.
             */
            Wrappers.<RuntimeException>sneakyThrow(ex);
          }
        };
      }

      /**
       * Reinier Zwitserloot who, as far as I know, had the first mention of this
       * technique in 2009 on the java posse mailing list.
       * http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html
       */
      public static <T extends Throwable> T sneakyThrow(Throwable t) {
          throw (T) t;
      }
  }
</code>```

And now I can just write:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            rethrow(f -> System.out.println(f.get(p)))
    );
</code>```

I am not sure that this is the best idiom to turn around the checked exceptions, but as I explained, I would like to have a more convenient way of achieving my first example without dealing with checked exceptions and this is the simpler way that I found to do it.

答:
sneakyThrow is cool!  I totally feel your pain.

If you have to stay in Java...

Paguro has functional interfaces that wrap checked exceptions so you don't have to think about this any more.  It includes immutable collections and functional transformations along the lines of Clojure transducers (or Java 8 Streams) that take the functional interfaces and wrap checked exceptions.

There is also VAVr and The Eclipse Collections to try out.

Otherwise, use Kotlin

Kotlin is 2-way compatible with Java, has no checked exceptions, no primitives (well, not the the programmer has to think about), a better type system, assumes immutability, etc.  Even though I curate the Paguro library above, I'm converting all the Java code I can to Kotlin.  Anything I used to do in Java I now prefer to do in Kotlin.

Title: Workaround for Java checked exceptions

ContentLicense: CC BY-SA 4.0


答:
When building the very first version of your software, always recalculate everything. You see, calculating stuff and storing them in memory is caching, and caching is an optimization, and any optimization before you have a complete product is a premature optimization, and premature optimization is the root of all evil.

Then, you have to consider that in embedded systems you may have many considerations which you might not have in non-embedded systems.

Do you actually have enough memory to spare for caching stuff?

Is this memory infinitely writable or does it wear down with each write?

Is your memory writable fast enough?  Some weird (mostly old) memories are far slower to write than to read, so calculating, writing once, and reading multiple times might have a comparable performance to recalculating multiple times.

Your code will already be complex enough and hard enough to debug due to peculiarities of the embedded system, do you really need to complicate your life even more by adding caching?

In short, unfortunately no, there is no general rule which says that it is always better to do this or always better to do that.

Title: Reading from Memory vs Performing an Operation

Body:
I'm learning to program microcontrollers and am trying to develop good habits:

Suppose I have a set of values which can be calculated based on what is already in memory.  As a general rule, is it always better to calculate the data once, and save it in memory, or is it always better to calculate it each time it's needed?

My guess would be that since reading and writing to memory is slower than processor operations, it would always be better to calculate something each time it's needed rather than storing the value in memory, provided the calculation is somewhat trivial.

Am I correct in my thinking?


答:
"Always" is always wrong. There are no general rules. Every case is different.

First, there's characteristics of your processor. The relative speed of reading/writing memory vs. performing operations is hugely different between processors. Enough different that it affects the decision.

Second, there is the question how often a result that was calculated once is used. If you calculate a*b a thousand times (with the same values a and b) then storing the result and loading when used is most likely to be a win; if you do it twice then this is much more dubious.

Third, there is correctness. If you recalculate a*b after a or b has changed then you get the correct result. If you rely on a stored result a * b after a change, then one of three things happens: 1. You get an old, stale result that is incorrect. 2. You check whether a or b has changed and recalculate the product if needed, which will eat up all or most of your advantage, or 3. you recalculate a * b in each place where you change a or b. Neither of these is much fun and hard to get correct.


问:
microservices: How to model related domain objects?
I have 2 domain objects: Project and Contract.  A project can have many contracts so in the database it is modeled as a classic one-to-many relationship.  Our question is this: How do you model the above in the context of microservices?  Do you (a) have 2 microservices ProjectService and ContractService?  or (b) Do you have one ProjectService which encompasses both Projects and Contracts?

We are thinking that answer (a) (i.e. 2 microservices ProjectService and ContractService) implies that one would have to call 2 services to retrieve and save the complete Project object hierarchy.  On the other hand, answer (a) completely decouples Projects from Contracts which may be a good thing in theory, but practically useless since a Contract cannot logically exist without a Project.

What is the correct approach here? Is answer (a) an example of the nano service anti pattern?

答:
I've looked at the nano services anti-pattern and indeed in my opinion option (a) is an example of it.

But also, you need to consider that your domain logic here, dictates the "Project-Contracts" coupling(it's by definition) therefore the finest(smallest) granularity of the microservice should include the whole thing(Project-Contracts coupling).

Suggestion:
I'd go for option (b) with the following twist, but only if you think that handling the Contracts alone requires too much code: consider having it as a private service class (not exposed to the outside world) that should only be constructed by a parameterised constructor which takes the ProjectID(or similar) as its parameter.


问:
Extensible way to create bash program
I have a bash script that should be extensible with additional functions with as little change to the script as possible.

The basic function is as follows. It loops through a list of files to check. The idea is that each check should be independent. A new check should be possible to add with the least possible change to the script as possible.

As bash is different from other programming languages, I think the way to do this is also different.

At the moment, a new check is added by creating a new script which is then added to the main script by calling it as an external command. That causes a lot of changes to the main script. As well the main script needs to accept aditional parameters to trigger the check script.

Is there any better way to do this? Any ideas?

答:
Put each "extension" in a separate bash script.

Come up with a special naming convention for them, like "x.*".

When your main script starts, have it first of all scan the directory for "x.*" and build a list of all matching extension filenames.

In each iteration of the loop, when you have a file to check, loop through the list of extension filenames and invoke each extension, passing it the filename of the file to check.  Make any other information that filters may (or may not) need available to the filters as environment variables.  Each filter uses whatever subset of that information it needs.

Of course this will not be so easy if each extension needs to communicate information back to the main script file, but you have not told us anything of that sort in the question. (Anyhow, even that is doable with special options which allow child scripts to modify the parent's environment.)

Title: Extensible way to create bash program


答:
Become intimately familiar with your IDE.

If your IDE is Visual Studio, then I highly recommend Sara Ford's book.

Title: How to become a "faster" programmer?

OwnerDisplayName: Jim G.


答:
k3b's answer really phrases it nicely:

a destructor in c++ is an implicit mechanism (automatically invoked)
  for releasing allocated resources while the try ... finally can be
  used as an explicit mechanism to do that.

As for "resources", I like to refer to Jon Kalb: RAII should mean Responsibility Acquisition Is Initialization.

Anyways, as for implicit vs. explicit this seems really to be it:

A d'tor is a tool to define what operations shall happen - implicitly - when the lifetime of an object ends (which often coincides with end-of-scope)

A finally-block is a tool to define - explicitly - what operations shall happen at end-of-scope.

Plus, technically, you are always allowed to throw from finally, but see below.

I think that's it for the conceptual part, ...

... now there are IMHO some interesting details:

try/catch/finally is lacking in that there's no fault block to run code that only should run in case of an exceptional scope-exit.

Destructors can be used to build finally machinery -- see SCOPE_EXIT, SCOPE_FAIL and SCOPE_SUCCESS in the folly library. See Andrei Alexandrescu: Error Handling in C++ / Declarative Control Flow (held at NDC 2014)

SCOPE_EXIT can replicate finally only so much, since it is technically perfectly fine to throw from finally while it simply doesn't work reliably from a destructor.

However, it would seem to me that people tend to think throwing from within finally is a bad idea anyway.

I do also not think that c'tor/d'tor need to conceptually "acquire" or "create" anything, apart from the responsibility to run some code in the destructor. Which is what finally does also: run some code.

And while code in a finally block certainly can throw an exception, that's not enough distinction to me to say that they are conceptually different above explicit vs. implicit.

(Plus, I'm not convinced at all that "good" code should throw from finally -- maybe that's another whole question to itself.)


问:
What is the hash value of each member of the group? Before modding?
This isn't an actual code related question but it relates to C. We are given:

Amy's club has grown and now includes the following members: Abel, Abigail, Abraham, Ada, Adam, Adrian, Adrienne, Agnes, Albert, Alex, Alfred, Alice

Find what value would be computed by Amy's hash function for each member of the group, before modding by the table size?

I'm not sure what they mean by BEFORE modding, because wouldn't we show the mod equation such as Abel: 4 % 6 = 4, as part of the answer?

Now, assume we use Amy's hash function and assign each member to a bucket by simply modding the hash value (obtained from part a) by the number of buckets. Determine how many elements would be assigned to each bucket (assume hashing with chaining) for a hash table of size 6. Do the same for a hash table of size 13.
c. What are the load factors of these two tables?

I would really appreciate an explanation as I'm not sure exactly how to calculate the answers to these problems and haven't found a good example, so a thorough explanation would be greatly appreciated.

答:
This looks like homework. I will not do your homework for you, but here are some nudges in the right direction. I recommend reading up on hash tables in general.

You have a hash function that is not provided in the question. It is used to place items in a hashtable.

First, you must calculate the hash values. Typically this function will consume an object of a given type and return some sort of integer value using the entire range of the integer type (e.g. 32 bits). This is what the first part of the question is asking: using the hash function, what are the hash values?

To place items in the hashtable, one must next scale those hash values to the size of the table. For example: if the table is size 6, the typical way to do this is take hash % 6 and that is the index into the hash table, or its "bucket."

The final part of your question is asking for the load factor. That is simply the ratio of elements to the total number of hash table entries (i.e. the array size).


答:
Consider this. When you "find annoying things (...) to clean up" and you make an executive decision to do so, you're cutting the rest of your team out of a priorities discussion and decision. You're letting your agenda trump everyone else because of your privileged relationship with the code. I don't think that's nice. From experience, it also leads to team/shareholder resentments.

Instead, create an issue/task for the clean-up/refactoring. While it's fresh in your mind, list the reasons it's important: estimates of increased stability, ease-of-maintenance, that sort of thing. Maybe include an estimation of effort depending on how your team works. Then in your next task selection/assignment/priorities meeting, present your refactoring task and position it against other tasks. As a team, decide when it should be completed.

Please don't think I'm telling you to throw out good sense in the name of principles. Use your head. If there's something ugly in the function you're editing, it's not a new refactoring task. Fix it and check everything in. If renaming the property you're working with to something more sensible affects a couple extra source files, it's not a new refactoring task. Fix it and check everything in. If, on the other hand, you don't like the way another developer (Mitch, I hate that guy) did something in a function you're not editing and said function appears to be working fine, leave it alone for now. Create a refactoring task and present your case to your team.

If refactoring is always down-voted by your team in favor of new features, start looking for another job. It's easier to find a job when you already have one.

Title: Workflow, editing things not in your current task

Body:
Usually when I program, I have a clear task ahead of me, but find annoying things I'd like to clean up as I go on.

Here I see three options:

Do it later (may forgot/have to spend time adding a ticket)

Do it now and commit it together with my current work (unclear)

Do it now and the commit it separately (have to find it, might make a mistake and go for option #2 unintentionally)

This is probably fairly basic, but what are some ways to circumvent this using svn/git/other?


问:
Is inline SQL still classed as bad practice now that we have Micro ORMs?
This is a bit of an open ended question but I wanted some opinions, as I grew up in a world where inline SQL scripts were the norm, then we were all made very aware of SQL injection based issues, and how fragile the sql was when doing string manipulations all over the place.

Then came the dawn of the ORM where you were explaining the query to the ORM and letting it generate its own SQL, which in a lot of cases was not optimal but was safe and easy. Another good thing about ORMs or database abstraction layers were that the SQL was generated with its database engine in mind, so I could use Hibernate/Nhibernate with MSSQL, MYSQL and my code never changed it was just a configuration detail.

Now fast forward to current day, where Micro ORMs seem to be winning over more developers I was wondering why we have seemingly taken a U-Turn on the whole in-line sql subject.

I must admit I do like the idea of no ORM config files and being able to write my query in a more optimal manner but it feels like I am opening myself back up to the old vulnerabilities such as SQL injection and I am also tying myself to one database engine so if I want my software to support multiple database engines I would need to do some more string hackery which seems to then start to make code unreadable and more fragile. (Just before someone mentions it I know you can use parameter based arguments with most micro orms which offers protection in most cases from sql injection)

So what are peoples opinions on this sort of thing? I am using Dapper as my Micro ORM in this instance and NHibernate as my regular ORM in this scenario, however most in each field are quite similar.

What I term as inline sql is SQL strings within source code. There used to be design debates over SQL strings in source code detracting from the fundamental intent of the logic, which is why statically typed linq style queries became so popular its still just 1 language, but with lets say C# and Sql in one page you have 2 languages intermingled in your raw source code now. Just to clarify, the SQL injection is just one of the known issues with using sql strings, I already mention you can stop this from happening with parameter based queries, however I highlight other issues with having SQL queries ingrained in your source code, such as the lack of DB Vendor abstraction as well as losing any level of compile time error capturing on string based queries, these are all issues which we managed to side step with the dawn of ORMs with their higher level querying functionality, such as HQL or LINQ etc (not all of the issues but most of them).

So I am less focused on the individual highlighted issues and more the bigger picture of is it now becoming more acceptable to have SQL strings directly in your source code again, as most Micro ORMs use this mechanism.

Here is a similar question which has a few different view points, although is more about the inline sql without the micro orm context:

https://stackoverflow.com/questions/5303746/is-inline-sql-hard-coding

答: Parameterized queries as well as the repository design pattern give you full control over what goes into the query to prevent injection attacks.  Inline SQL in this case is not an issue other than readability for large and complex queries, which should be in stored procedures anyway.</p>


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
Know what you want to do and have an interest in it

Spend a few hours researching code on how to do it

Copy and paste code to achieve the end result

Work on a basic gui to get the job done, DO NOT SPEND TIME TO MAKE IT LOOK PRETTY

Test and debug

Work on a pretty gui

Title: How to become a "faster" programmer?

OwnerDisplayName: Matt S.


问:
Are there practical benefits from encapsulating JS inside class.create?
I am working on this web application that already has a mechanism that allows a developer to define server side JavaScript functions that can then be called by other server side JS code.

There are two ways to define these functions.

This way...

```<code>function iAmFunctionA(arg) {
   ...some code...
}

function iAmFunctionB(arg) {
   ...some other code...
}
</code>```

...and by an option that encapsulates the functions inside a separate object (I think this is because the web application has Prototype.js embedded)...

```<code>var iAmAClass = Class.create();
   iAmAClass.prototype = {
      iAmFunctionA: function(arg) {
         ...some code...
      },

      iAmFunctionB: function(arg) {
         ...some other code...
      },

   type: 'iAmAClass'
}
</code>```

This latter type is then called by other server side JS like so:

```<code>var a = new iAmAClass();
var someRetVal = iAmAClass.iAmFunctionA(arg);
</code>```

The question I wanted to ask is: are there any practical benefit(s) from encapsulating JavaScript inside an object, and if so, what would that be?

答:
I think this is really trying to put Object Oriented thinking into JavaScript.  Your code looks just like this example:
Create an Object-oriented JavaScript Class Constructor from HTML Goodies.

Object Oriented Programming is an organizational technique.  If you have a User data structure, it might have fields like:

```<code>firstName
lastName
age
</code>```

You might have functions that work with Users like,

```<code>createUser()
deleteUser()
changeFirstName()
addUserToCompany()
</code>```

You could just throw all these things around willy nilly, or you could put all the user-related data and functions in one place - a User class.  Maybe that last addUserToCompany() function belongs more on the Company class than the User class.  It's not a perfect system.  But you shouldn't have to look for that function anywhere but the User and Company classes, so at least it narrows down where you'd sensibly look for things.

Encapsulation usually means (roughly) "hiding."  You hide things to limit the ways they can be used.  If something has no moving parts, you're less likely to break it.  So you hide all the sensitive stuff - hopefully more effectively than you would by adding a comment like // Don't touch this!

Unfortunately, everything in JavaScript is global, visible, and mutable.  The only way to encapsulate things in JavaScript is to put them inside functions.  You con't get most of the guarantees/benefits of OOP in JavaScript.  But some people like OOP.  Some problems are best solved with OOP, even if using JavaScript this way is a bit artificial.

What you are seeing here is someone setting up data and functions inside a closure to make the details of those things less public.  I'm not sure how effective it is, since JavaScript objects provide almost no guarantees.

Most likely, the benefit in this case is that the person who wrote the code gets to think about code the way they are used to thinking in an Object Oriented language like Java.  If you like to think that way, then it helps you.  If not, then I don't see the benefit of trying to do OOP in JavaScript either.

But if your question is specifically about encapsulation, then as Robert Harvey mentioned, that's almost always a good thing.  And putting things inside functions (or "closures") is the only way to encapsulate in JavaScript (at least until ES6).

Body:
I think this is really trying to put Object Oriented thinking into JavaScript.  Your code looks just like this example:
Create an Object-oriented JavaScript Class Constructor from HTML Goodies.

Object Oriented Programming is an organizational technique.  If you have a User data structure, it might have fields like:

firstName
lastName
age

You might have functions that work with Users like,

createUser()
deleteUser()
changeFirstName()
addUserToCompany()

You could just throw all these things around willy nilly, or you could put all the user-related data and functions in one place - a User class.  Maybe that last addUserToCompany() function belongs more on the Company class than the User class.  It's not a perfect system.  But you shouldn't have to look for that function anywhere but the User and Company classes, so at least it narrows down where you'd sensibly look for things.

Encapsulation usually means (roughly) "hiding."  You hide things to limit the ways they can be used.  If something has no moving parts, you're less likely to break it.  So you hide all the sensitive stuff - hopefully more effectively than you would by adding a comment like // Don't touch this!

Unfortunately, everything in JavaScript is global, visible, and mutable.  The only way to encapsulate things in JavaScript is to put them inside functions.  You con't get most of the guarantees/benefits of OOP in JavaScript.  But some people like OOP.  Some problems are best solved with OOP, even if using JavaScript this way is a bit artificial.

What you are seeing here is someone setting up data and functions inside a closure to make the details of those things less public.  I'm not sure how effective it is, since JavaScript objects provide almost no guarantees.

Most likely, the benefit in this case is that the person who wrote the code gets to think about code the way they are used to thinking in an Object Oriented language like Java.  If you like to think that way, then it helps you.  If not, then I don't see the benefit of trying to do OOP in JavaScript either.

But if your question is specifically about encapsulation, then as Robert Harvey mentioned, that's almost always a good thing.  And putting things inside functions (or "closures") is the only way to encapsulate in JavaScript (at least until ES6).


问:
Why do programmers define programming models to replace C/POSIX for parallelism?

Providers of new computer architectures regularly try
  to introduce new programming models, e.g. recently
  CUDA/OpenCL for GPGPUs, and displace C/POSIX as the
  control interface to platform parallelism. (Poss & Koening, AM3: Towards a hardware Unix accelerator for many-cores, 2015)

Why do architecture designers try to design new programming models to displace C/POSIX for parallel computing? Is C/POSIX not well suited to multiprocessors or did the original authors of C/POSIX not have the need for parallel computing in mind at C/POSIX design time? Or is it the case that programmers need more capabilities than C/POSIX can deliver,thus resorting to new designs e.g. CUDA/OpenCL, etc.?

答:
Compare POSIX threads and Grand Central Dispatch, for example. I have code that dispatches to four threads in eight lines of code. With POSIX, that would all be an absolute nightmare. </p>

<p>On the other hand, CUDA / OpenCL are not about multithreading at all, but about using massive vector abilities. (They can do multithreading as well, but vectorizing is the important thing). </p>

Body:
Compare POSIX threads and Grand Central Dispatch, for example. I have code that dispatches to four threads in eight lines of code. With POSIX, that would all be an absolute nightmare.

On the other hand, CUDA / OpenCL are not about multithreading at all, but about using massive vector abilities. (They can do multithreading as well, but vectorizing is the important thing).


问:
How to classify bug severity to complement our priority classification?
At my current job we have Low, Medium, High priority bugs.

Low priority bugs are small errors that don't stop shipping or cause real trouble for any user.

Medium priority bugs cause some internal users trouble but have known workarounds.

High priority bugs are problems that our customers will see, can corrupt data, or crash a system.

How to classify bug severity to complement our priority classification?

答:
Classify bugs by their annoyance factor, which can stop people from buying the software. A bug that doesn't affect shipping or causes real trouble to users may be annoying the **** out of me every time I run into the bug. And eventually you lost a user and part of your income.

Now if you combine that kind of bug with a user interface that has been changed for no apparent reason and with no visible benefit for the user, then you have an absolute winner that will make people hate your software.

Don't allow that to happen. Don't ship with bugs that make customers think that you don't give a ****.


答:
There is a distinction between SIMD parallel programming and the more traditional parallel programming model that POSIX uses.

SIMD is the model that CUDA, OpenCL, etc. use. There is a single set of instructions that are executed simultaneously by many threads, each operating on their own pool of data. This is very useful for thing like 3-D graphics, where the same transformations are applied to a large number of points.

The POSIX model assumes that each thread runs asynchronously, and each thread can potentially execute totally different code.

Both models have their strengths and weaknesses -- that's why they are different. POSIX is much more flexible, but CUDA/OpenCL/etc. can take advantage of specialized hardware, running thousands of (usually simpler) threads at a time.

Title: Why do programmers define programming models to replace C/POSIX for parallelism?

Body:
Providers of new computer architectures regularly try
  to introduce new programming models, e.g. recently
  CUDA/OpenCL for GPGPUs, and displace C/POSIX as the
  control interface to platform parallelism. (Poss & Koening, AM3: Towards a hardware Unix accelerator for many-cores, 2015)

Why do architecture designers try to design new programming models to displace C/POSIX for parallel computing? Is C/POSIX not well suited to multiprocessors or did the original authors of C/POSIX not have the need for parallel computing in mind at C/POSIX design time? Or is it the case that programmers need more capabilities than C/POSIX can deliver,thus resorting to new designs e.g. CUDA/OpenCL, etc.?


问:
Swift functions vs computed properties
Say I have have a class Event as follows:

```<code>class Event {
    private var attendees: [Person] = []

    // Case 1
    //*******
    // Should I use a func…
    func countOfAttendees() -> Int {
        return attendees.count
    }

    // …or a var
    var countOfAttendees: Int {
        return attendees.count
    }

    // Case 2
    //*******
    // Should I use a func…
    func countOfPaidAttendees() -> Int {
        return attendees.filter({$0.hasPaid}).count
    }

    // …or a var
    var countOfPaidAttendees: Int {
        return attendees.filter({$0.hasPaid}).count
    }
}
</code>```

Is it best practice to use functions or computed properties in the 2 cases indicated above?

答:
I'd use a func. Object-oriented programming works just fine without computed properties. Because you are getting a value back that was computed/filtered some may argue that a computed property feels right. But here's my complaint, if you do that then readability takes a hit, because it feels like a value.

In this context it wouldn't make sense to try to assign the computed value (and luckily the IDE helps us avoid this) but what if I try to assign something that is computed but looks like a value?

```<code>event.countOfAttendees = 0; // not possible
</code>```

While using func the caller know's you aren't dealing with a value directly:

```<code>event.countOfAttendees()
</code>```

I think if its a behavioral object it should look like it behaves rather than looking like a data structure. If your object is dumb and doesn't have any behavior then why try to encapsulate it? In that case you might as well just have attendees be public

Title: Swift functions vs computed properties

Body:
I'd use a func. Object-oriented programming works just fine without computed properties. Because you are getting a value back that was computed/filtered some may argue that a computed property feels right. But here's my complaint, if you do that then readability takes a hit, because it feels like a value.

In this context it wouldn't make sense to try to assign the computed value (and luckily the IDE helps us avoid this) but what if I try to assign something that is computed but looks like a value?

event.countOfAttendees = 0; // not possible

While using func the caller know's you aren't dealing with a value directly:

event.countOfAttendees()

I think if its a behavioral object it should look like it behaves rather than looking like a data structure. If your object is dumb and doesn't have any behavior then why try to encapsulate it? In that case you might as well just have attendees be public


问:
How to avoid the pitfalls of static analysis
I'm working at a company that would score 11 on Joel Test - at least on paper.

In practice, however, nothing works quite as well as expected, and the project has been on DEFCON 1 for half a year. Now, most of my peers are happy if they can go back home at 6pm - on Sunday.

One of the apparently good practices that struck me as not working is the use of static analysis tools. The project both tracks gcc -Wall warnings and a proprietary and very expensive "C/C++" tool.

Gcc warnings do more often than not point to real(if most of the time inoffensive) bugs.

The proprietary tools, however, list things such as implicit casts and sizeof'ing a string literal. Implicit casts are also blacklisted on their stylebook.

The standard practice is that people is pressed to make every single warning shut up. Note that this does exclude warnings that are predominantly false positives, this is not the problem.

The result is:

People add type casts to every rvalue and to every argument hiding real problematic type mismatches in the process.

People introduce off by one bugs, or use a different problematic language feature.(strlen instead of sizeof, strncpy instead of strcpy, etc.)

The warnings are silenced.

The bug reports start rolling in.

The main point is the original code was working and written by people who were playing safe within their language abilities whereas the fixes were not.

Now, I don't really think this company can be saved. However, I would like to know if there is a better, preferably working, way to use the "pro" tools or if I should just avoid using them altogether in case I am the one making the decision in the future.

A solution which doesn't assume all programmers are geniuses that can't err. Because well, if they are, then there is no need to use the tools in the first place.

答:
In addition to user29079's excellent answer, I would like to add one more deficiency of the C language which adds to the problem.  I was not aware of this deficiency until I moved on to Java.

The purpose of a warning is to bring to the attention of the writer and future readers of the code the fact that there is something fishy going on.  That, as a concept, is perfectly fine: the more warnings you have enabled, more fishy things you discover.

What is dead wrong, is the notion that every single little fishy thingy must be fixed at all costs, by changing code. That is what caused the problem that the OP is describing: the botched attempts to hastily make warnings go away by altering code which is working just fine.

At the same time, we don't want our code spewing out hundreds of warnings every time we compile, because pretty soon warnings become meaningless, and nobody pays any attention to new warnings anymore.

So, this seems to be a case of conflicting goals; a contradiction.

A very good solution to this seemingly impossible quandary is to be able to selectively suppress a certain warning on a statement by statement basis, so that we can suppress it precisely there where we want to indicate that we do really know what we are doing, without having to alter any code.

Java has a nice solution to this, with the @SuppressWarnings( "" ) annotation.  If you are making, say, a so-called unchecked conversion in java, the compiler issues a warning to bring this to your attention, you examine it, you determine that this is one more of those cases where you know what you are doing, so you precede the offending statement with a @SuppressWarnings( "unchecked" ) annotation which affects only the statement which immediately follows it, and you proceed with your life.

So, the warning goes away, the code remains unaltered, and the suppression annotation stands there, colored green by syntax highlighting, to document the fact that an iffy conversion is taking place, but the author promises is good. (*)  Everyone is happy.

In java you can even prefix individual parameters to functions with @SuppressWarnings(), so as to disable a specific warning which may be issued on that specific parameter only.

However, as far as I know, C never supported any standard mechanism for selectively suppressing warnings on statements, and certain compilers that implemented their own proprietary mechanisms did so in a shrewd fashion, for example the #pragma warning (nnn:N) directives of Microsoft C.  The problem with these directives is that you need two lines of directives in order to both suppress a warning for a single statement and leave that warning enabled for statements that follow.  Therefore, C programmers are highly unlikely to pick up the habit of suppressing a warning on an individual statement basis, even when they know that this particular warning on this particular statement is okay.

(*) someone might argue that if you allow this, then every programmer in the house will be suppressing warnings without giving them any thought; the answer to this is that you may do everything you can to help the programmers do their job better, but there is nothing you can do if they actively decide to sabotage you.


问:
Does this code solve the square/rectangle Liskov Substitution Principle example?
I just wanted to check that I understand the LSP correctly and can solve it. I am taking the classic rectangle/square problem and attempting a solution:

class Rectangle{
    public $width;
    public $height;

    function setWidth($width){
        $this->width = $width;
    }

    function setHeight($height){
        $this->height = $height;
    }
}

class Square extends Rectangle{

    function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }
}
```

<p>If you had some code like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(Rectangle $rect){
  $rect->setWidth(10);
  $rect->setHeight(30);
  $this->assertEquals(10,$rect->width);
  $this->assertEquals(30,$rect->height);
}
</code>```

Then obviously rectangles and squares are not interchangeable, as square introduces a constraint to the parent class. Therefore, a square should not inherit from rectangles.

But surely we can agree that both square and rectangle are four sided shapes? This is my proposed solution, based on this premise:

abstract class AFourSidedShape{
    public $width;
    public $height;

    abstract public function __construct($width,$height);

    public function scaleUp($percentage){
        $this->height = $this->height + (($this->height / 100) * $percentage);
        $this->width = $this->width + (($this->width / 100) * $percentage);
    }

    public function scaleDown($percentage){
        $this->height = $this->height - (($this->height / 100) * $percentage);
        $this->width = $this->width - (($this->width / 100) * $percentage);
    }
}

class Rectangle extends AFourSidedShape{
    function __construct($width, $height){
        $this->width = $width;
        $this->height = $height;
    }
}

class Square extends AFourSidedShape{
    function __construct($width, $height){
        if($width != $height){
            throw new InvalidArgumentException('Sides must be equal');
        }else{
            $this->width = $width;
            $this->height = $height;
        }
    }
}
```

<p>Our client code should be changed to something like:</p>

<pre class="lang-php prettyprint-override"><code>function changeSize(AFourSidedShape $shape){
  $origWidth = $shape->width;
  $origHeight = $shape->height;
  $shape->scaleUp(10);
  $this->assertEquals($origWidth + (($origWidth/100) * 10),$shape->width);
  $this->assertEquals($origHeight + (($origHeight/100) * 10),$shape->height);
}
</code>```

My theory is: rectangles and squares really are both foursidedshapes, so there shouldn't be a problem with inheriting from the foursidedshape abstract class. Whilst the square is still adding extra constraints in the constructor (i.e. throwing an error if the sides aren't equal), it shouldn't be a problem since we haven't implemented the constructor in the abstract parent class, and so client code shouldn't make assumptions about what you can/cannot pass into it anyway.

My question is: have I understood LSP, and does this new design solve the LSP problem for square/rectangle?

When using interfaces as suggested:

interface AFourSidedShape{
    public function setWidth($width);
    public function setHeight($height);
    public function getWidth();
    public function getHeight();
}

class Rectangle implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($width,$height){
        $this->width = $width;
        $this->height = $height;
    }

    public function setWidth($width){
        $this->width = $width;
    }

    public function setHeight($height){
        $this->height = $height;
    }

    //getwidth, getheight
}

class Square implements AFourSidedShape{
    private $width;
    private $height;

    public function __construct($sideLength){
        $this->width = $sideLength;
        $this->height = $sideLength;
    }

    public function setWidth($width){
        $this->width = $width;
        $this->height = $width;
    }

    public function setHeight($height){
        $this->height = $height;
        $this->width = $height;
    }

    //getwidth, getheight
}
```

答:
AFoursidedShape hides information about the dependencies between height and width,
so LSP is not violated as is the case with Square inhereting from Rectangle.

The class rectangle and square are representations of squares and rectangles, therefor they do not necessary share the same relationship as what they represent.
 In other words a mathemtical Square has a relationship with mathemtical rectangle, but that does not imply the class square must necesseraly have same relationship with class rectangle.
If we still want to treat Square as a Rectangle another way of doing it without violating LSP could be to have an interface thats called ARectangleReader which only has contract for the getters getHeight and getWidth which is implemented by the Square class  and Rectangle class.

Another way to think about it: does a mutable Square really behave like a mutable Rectangle?


答:
learn Design patterns. They help you understand problems, make you a better programmer -> will let you program a lot faster since you have already solutions for several problems prepared in mind

extract repetitive parts in your program. If there is some logic which repeats throughout several programs you write, consider generalizing them and extracting them to some class library which you can then reuse on new applications you write. Standardize things: invest some time into finding out how certain repetitive tasks are done best. Document the steps for achieving. Next time you will exactly know how to solve/apply them.

KISS principle

Code generation will be useful (once a useful tool is available). Generators start to gain popularity, recently.

Note: Just making things work is worse!! As some mention just to hack in things till they work will make you faster just for the moment. Bugs will come in however which somehow count also in terms of how fast you program. If I have to write some piece of functionality and I invest in writing it good, having a good design, possibly well tested (with Unit tests) and say I'll need half a day. But assume that was it and your feature works and you don't have to touch it again. Another programmer, just focused on a fast achievement of his goal, will make (possibly) a bad design, due to missing testing he'll not consider (be aware of) boundary, exceptional cases. He'll need 2 hours (let's say). Bugs will come in, he'll again have to touch the code, fix it, possibly extend it (hours will be invested again). Code will be hard to maintain etc...resumé: at the end he'll spend much ore time and frustration will be higher.

Title: How to become a "faster" programmer?

OwnerDisplayName: Juri