问:
Enforcing aggregate rules in purchase management domain
I'm having problems defining the aggregate boundaries (and maybe even the aggregate root) to enforce the transactional consistency rule. Let me first describe the problem domain.

In our domain we have a project that contains a budgeted plan, which in turn contains hundreds of purchase items that need to be purchased. Some of these items are selected to form a purchase task. When this occurs, the item should be moved from the budgeted plan to the purchase task. The flow of the item is of importance (needs to be audited for later review), so the item must be an entity and have an identifier.

My current design would have the purchase task as the aggregate root and it would know all its items. I'm inclined to leave the budgeted plan outside of this aggregate as it contains lots of items. But then I began to doubt myself.

Vaughn Vernon describes that a well designed aggregate should be "based on true business rules that require specific data to be up-to-date at the end of a successful database transaction". In my scenario the purchase item that is moved from the budgeted plan to a designated purchase task should be removed from the list of items in the budgeted plan. Now if my aggregate would not include the budgeted plan and all the hundreds of items there, I cannot enforce this rule. If I do include it, the aggregate grows large and will have to load the all the budgeted plans items (hundreds, maybe thousands) for validation to succeed.

As the purchase item is also an entity that needs to be trackable and modifiable I think that should be it's own aggregate root. Then the item should be referenced only by its ID from both the budgeted plan and the purchase task. Is this correct?

The main question is: How should I define my aggregate boundaries and roots to be able to enforce the transactional consistency rule in this domain?

答:
Project plan could be an aggregate and budgeted plan and purchase task could be entities inside that aggregate. The project knows all the data it needs to make the decisions. There can be quite a bit of data but you can utilize lazy loading and custom sql queries to optimize memory and cpu usage.

Alternative design:
Budgeted plan and purchase task could be aggregates. You save some memory but you now need to modify two aggregates at the same time when you are moving items between the two which probably means you should use eventual consistency between the two aggregates. See here how this can be achived.


问:
Why does presence of value evaluate as "Truthy" in Python? [e.i. Types evaluate True in conditionals]
Example:

```<code>if float: print('float is true?')
</code>```

returns:

Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?

答:
Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?

Simple explanation:

Because they do, by definition.  Sorry if that seems like a tautology, but that really is the correct answer: this is the arbitrary way it works because that is the arbitrary way it is specified to work in the arbitrary, canonical rules of the language.

Philosophical explanation:

Have a look at the Zen of Python, which states:

Special cases aren't special enough to break the rules.

If the rules are that "this specific set of values are falsy and everything else is truthy," then even though it seems nonsensical to have a reference to a type being either truthy or falsy, that's a special case, and it's not special enough to break the rules.

Flame bait explanation:

Because Python lacks a proper static type system, in which the only True and False values would be True and False, and anything else would be rejected at compile time.  And since you can't do that in a dynamic language, Python takes the easy way out instead of spending extra effort to do it "the right way" (and good luck defining that in this context!) even when it means accepting obviously-invalid and nonsensical code.

Take your pick ;-)

ContentLicense: CC BY-SA 3.0


问:
Does music increase your productivity?
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)

答:
I think we should be the ones who sing while programming and I agree with G.K. Chesterton who wrote in Tremendous Trifles nearly 100 years ago:

If reapers sing while reaping, why
  should not auditors sing while
  auditing and bankers while banking? If
  there are songs for all the separate
  things that have to be done in a boat,
  why are there not songs for all the
  separate things that have to be done
  in a bank? As the train from Dover
  flew through the Kentish gardens, I
  tried to write a few songs suitable
  for commercial gentlemen. Thus, the
  work of bank clerks when casting up
  columns might begin with a thundering
  chorus in praise of Simple Addition.

"Up my lads and lift the ledgers,
  sleep and ease are o'er. Hear the
  Stars of Morning shouting: 'Two and
  Two are four.' Though the creeds and
  realms are reeling, though the
  sophists roar, Though we weep and pawn
  our watches, Two and Two are Four."

"There's a run upon the Bank--Stand
  away! For the Manager's a crank and
  the Secretary drank,   and the Upper
  Tooting Bank
            Turns to bay! Stand close: there is a run On the Bank. Of our
  ship, our royal one, let the ringing
  legend run,   that she fired with
  every gun
            Ere she sank.

That would increase our productivity the same way sailor's songs increase their productivity.  If gets everyone on the same page and directs our goals to a common point.

ContentLicense: CC BY-SA 2.5

Title: Does music increase your productivity?


答:
The Python language is strongly influenced by C. And C is a horrible language that didn't even have a boolean type until C99. Instead, it has integers. Anything that looks like a zero integer is false, anything else is true. It turns out that this is mightily convenient.

Wanna test for a null pointer? Unlike Java, you don't have to spell out if (thing != null) foo(thing); – a if (thing) foo(thing); suffices.
Wanna check if we reached the end of a string? Just dereference it in a conditional:

```<code>char c;
while ((c = *str++)) do_something(c);
</code>```

Wanna check if an array contains any items? Just test for the length:

```<code>int n;
...;
if (n) we_have_items();
</code>```

So conceptually, a conditional has two forms:

a predicate form with some expression that evaluates to a boolean-interpretable value.

a container form with a single variable to check that this container is not-empty.

While Python has actual boolean types rather than overloading integers, it keeps this very popular mechanism for collections. For example, None (Python's null equivalent), empty strings "", empty lists [], and empty dicts {} all evaluate to False in a boolean context. This usually does what you want, and if it doesn't, you can be explicit about your requirements. For example, you can specifically test that a variable is not None:

```<code>if x is not None:
  do_something_with(x)
</code>```

However, if you know that name is an optional string, then writing

```<code>if name:
  print("hello, ", name)
else:
  print("name required!")
</code>```

is much more comfortable than

```<code>if bool(name):  # manually force to-bool conversion
  ...
</code>```

or

```<code>if name is not None and len(name):  # explicitly state your intent: at least one character
  ...
</code>```

or

```<code>if name is not None and bool(len(name)): # what the above example really means
   ...
</code>```

or

```<code>if name is not None and len(xs) > 0:  # even more explicit
  ...
</code>```

It is important to note that these implicit conversions are not black magic that pull the comfy rug of type safety away from under your feet. In Python, these conversions always happen quite explicitly, but if you pass a function or a builtin some value, it may perform any such conversions on that argument. For example, you can explicitly request a bool conversion via bool(some_value). So if you want to, you can think of the if EXPRESSION: ... builtin as being implemented like:

```<code>def if(EXPRESSION, then, else):
  real_if bool(EXPRESSION):
    then()
  real_else:
    else()
</code>```

You can also define your own to-bool conversion for your own classes, by implementing the special __bool__(self) method. But careful! Conversions and operator overloading can get quite confusing for a user unless the semantics are obvious and intuitive. In Python, it is considered sufficiently clear for a to-bool conversion to test whether a collection or container is empty. For non-containers, it might be a good idea to use an ordinary, named method instead.

So why does it make sense for values to evaluate to True even when no to-bool conversion has been defined? User-defined types generally have reference semantics, i.e. the variable holds a pointer to the value, not the value itself. As we have seen, the if (pointer) ... C idiom tests whether a pointer is not empty, so it makes some sense to extend it even to Python which does not have reified pointers. So the conditional here does not test whether the value is true or false, but whether the variable currently holds a value. If the type had value semantics, I would find such a to-bool conversion highly confusing, but that might just be the C++-programmer in me speaking.

Title: Why does presence of value evaluate as "Truthy" in Python? [e.i. Types evaluate True in conditionals]

Body:
Example:

```<code>if float: print('float is true?')
</code>```

returns:

Why do all objects other than ones explicitly defined as False or "False" evaluate truthfully?

Body:
The Python language is strongly influenced by C. And C is a horrible language that didn't even have a boolean type until C99. Instead, it has integers. Anything that looks like a zero integer is false, anything else is true. It turns out that this is mightily convenient.

Wanna test for a null pointer? Unlike Java, you don't have to spell out if (thing != null) foo(thing); – a if (thing) foo(thing); suffices.
Wanna check if we reached the end of a string? Just dereference it in a conditional:

char c;
while ((c = *str++)) do_something(c);

Wanna check if an array contains any items? Just test for the length:

int n;
...;
if (n) we_have_items();

So conceptually, a conditional has two forms:

a predicate form with some expression that evaluates to a boolean-interpretable value.

a container form with a single variable to check that this container is not-empty.

While Python has actual boolean types rather than overloading integers, it keeps this very popular mechanism for collections. For example, None (Python's null equivalent), empty strings "", empty lists [], and empty dicts {} all evaluate to False in a boolean context. This usually does what you want, and if it doesn't, you can be explicit about your requirements. For example, you can specifically test that a variable is not None:

if x is not None:
  do_something_with(x)

However, if you know that name is an optional string, then writing

if name:
  print("hello, ", name)
else:
  print("name required!")

is much more comfortable than

if bool(name):  # manually force to-bool conversion
  ...

or

if name is not None and len(name):  # explicitly state your intent: at least one character
  ...

or

if name is not None and bool(len(name)): # what the above example really means
   ...

or

if name is not None and len(xs) > 0:  # even more explicit
  ...

It is important to note that these implicit conversions are not black magic that pull the comfy rug of type safety away from under your feet. In Python, these conversions always happen quite explicitly, but if you pass a function or a builtin some value, it may perform any such conversions on that argument. For example, you can explicitly request a bool conversion via bool(some_value). So if you want to, you can think of the if EXPRESSION: ... builtin as being implemented like:

def if(EXPRESSION, then, else):
  real_if bool(EXPRESSION):
    then()
  real_else:
    else()

You can also define your own to-bool conversion for your own classes, by implementing the special __bool__(self) method. But careful! Conversions and operator overloading can get quite confusing for a user unless the semantics are obvious and intuitive. In Python, it is considered sufficiently clear for a to-bool conversion to test whether a collection or container is empty. For non-containers, it might be a good idea to use an ordinary, named method instead.

So why does it make sense for values to evaluate to True even when no to-bool conversion has been defined? User-defined types generally have reference semantics, i.e. the variable holds a pointer to the value, not the value itself. As we have seen, the if (pointer) ... C idiom tests whether a pointer is not empty, so it makes some sense to extend it even to Python which does not have reified pointers. So the conditional here does not test whether the value is true or false, but whether the variable currently holds a value. If the type had value semantics, I would find such a to-bool conversion highly confusing, but that might just be the C++-programmer in me speaking.


问:
Best way to handle nulls in Java?
I have some code that is failing because of NullPointerException.  A method is being called on the object where the object does not exist.

However, this led me to think about the best way to fix this.   Do I always code defensively for nulls so that I future proof code for null pointer exceptions, or should I fix the cause of the null so that it won't occur downstream.

What are your thoughts?

答:
Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

```<code>String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}
</code>```

If each of these may or may not return a successful value, you can change the APIs to Optionals:

```<code>String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");
</code>```

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/

@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.

Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.

Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

Title: Best way to handle nulls in Java?

Body:
Don't use null, use Optional

As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.

It's impossible to tell that could be null and what couldn't be.

Java 8 introduces a much better pattern: Optional.

And example from Oracle:

String version = "UNKNOWN";
if(computer != null) {
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null) {
    USB usb = soundcard.getUSB();
    if(usb != null) {
      version = usb.getVersion();
    }
  }
}

If each of these may or may not return a successful value, you can change the APIs to Optionals:

String name = computer.flatMap(Computer::getSoundcard)
    .flatMap(Soundcard::getUSB)
    .map(USB::getVersion)
    .orElse("UNKNOWN");

By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.

If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.

A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/

@Nonnull, @Nullable

Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.

Check when it makes sense

Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.

On the other hand, if null could be used and mean something, make sure to use it.

Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.

ContentLicense: CC BY-SA 4.0


问:
Do classes in a JRE library support observable and/or asynchronous reads from external/non-JRE assemblies?
How can I implement my cross-platform library (e.g. on JRE) to operate in a thread-safe manner on object references, so that native front-ends on other platforms can observe the object and take advantage of Observable patterns?

A little background--there is a concept of data binding used in most front-end frameworks. In C# and Java this is related to the Observable trait that gives a class the ability to fire events when changes happen, to which multiple controls or "observers" may subscribe. This way the observers don't have to keep polling/reading the resource, comparing for updates.

I want to work on an analysis engine that makes changes to lists of data over time. It would be nice to be able to have the front-end be able to observe these lists while the analysis is running. It seems to me this would require the front-end to be able to pass an object to the analysis engine, written in a library that hopefully is cross-platform, and be able to make thread-safe reads to that object. Or else, have the library satisfy observability contracts.

The way this is handled in older Unix-style CLI engines is to use stdin/stdout/stderr, and have the engine post updates on regular intervals. This requires standard overhead and text parsing that I would rather avoid, if possible.

答:
You can create an integration tier over your library's model using (for example) the apache camel integration framework. The Netty component probably could fit your needs. With an observable pattern your integration tier should transform your model's received changes and notify them to the front-end subscribers.
Another similar way to interpret your requirement is to think about an event-driven architecture where when your model changes, the observer listeners in your integration tier publishes a message in a JMS Topic so connected subscriptors in the front-ends will receive them.</p>


问:
How should one model an ExchangeService object (in ews-java-api) for sharing MS Exchange connections?
I am creating an application which uses ews-java-api to connect to an MS Exchange server. Once the connection is authenticated, the api dictates use of ExchangeService object for searching mailboxes, fetching mails and then reading its contents.

The emails are read by different classes down the line for analysis and actions depending upon email content. All these classes must need one pre-authenticated instance of ExchangeService object.

The instance of the object is obtained as -

```<code>ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials("emailAddress", "password");
service.setCredentials(credentials);
</code>```

In future there may be requirements to add more classes down the line as needed for more functionalities. All of them would be using the same instance of ExchangeService object.

My question is how should I design the sharing of ExchangeService instance among all these classes down the line? Keeping in mind that no one should inadvertently call the "close()" method on that instance, until whole of the application finishes.

On first look it might appear as a Database connection pool design sort of stuff, but its not. This application runs periodically every 5 minutes and connects to the Exchange server, does its job of analyzing unread mails (with all behavioral classes) and then ideally should close the connection.

One thought of singleton pattern also crossed my mind, but the issue of calling the "close()" method still remains.

Any design suggestion to simplify the system?

Thanks in Advance!

答:
Do all the classes really need access to the entire object? Otherwise, this looks like a correctness problem (but not in a bad way), rather than a design problem. One approach is to consider a code contract enforced by a caller:

```<code>f(g, exchange-object) {
   /* pre-condition/invariant */
   assert(exchange-object.open() == true);
   g(exchange-object);
   /* post-condition/invariant */
   assert(exchange-object.open() == true);
   }
..
f ( obj-on-the-line.g, exchange-object )
..
</code>```

More info:
http://c2.com/cgi/wiki?DesignByContract

Body:
Do all the classes really need access to the entire object? Otherwise, this looks like a correctness problem (but not in a bad way), rather than a design problem. One approach is to consider a code contract enforced by a caller:

f(g, exchange-object) {
   /* pre-condition/invariant */
   assert(exchange-object.open() == true);
   g(exchange-object);
   /* post-condition/invariant */
   assert(exchange-object.open() == true);
   }
..
f ( obj-on-the-line.g, exchange-object )
..

More info:
http://c2.com/cgi/wiki?DesignByContract


问:
Is there a design pattern for managing deep many-to-many relationships?
I'm having trouble defining this data pattern I've come across working on several applications.

It consists of:

An object type which is composed of many objects itself

A second object type, where each instance 'has many' of the first object

And, each of the sub-objects of the first object are modifiable per each association to the second object type.

A simple example might be:

A programming course consisting of a set of lessons

The lessons are composed of a set assignments.

A course can be assigned to a student.

However, once a course is assigned to a student each lesson and/or assignment can be customized to that student, with removals and additions, to the point where the original course may be unrecognizable.

In my solutions, what this results in is:

On assignment of a course to a student, the course is loaded into memory. Then for each sub-object, a student/sub-object relationship object is generated with the appropriate metadata. Essentially, I'm using the original object as a template to generate the required customizable objects.

This results in a huge amount of data as the sub-objects become more complex and numbered. I'm wondering if there is some optimization or pattern to reduce the amount of logic/complexity required to manipulate this data pattern.

答:
I'm finding it hard to believe, under the presence of a data-store or persistence, that you would need to have objects with this kind of depth at any given point in a run-time. Is this for CRUD GUI's? If so, then I would suggest changing your approach from the start. IE:

Identify the substructure necessary for the Student to show, and statefully store its origin index back to the db, and statelessly update that, going to or from the view and the backend db.


问:
Are debugging skills important to become a good programmer?
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>

答:
Yes its very important

About that particular candidate, it is possible that s/he was not familiar enough with code-base x to debug it.

A good problem solver should be able to debug, as all that is usually required is to have a very logical method/approach.


答:
If you can't debug you're pretty much not a programmer at all, let alone a good one.

Debugging is a real, practical application of not only technical skills but also analysis ability and thought processes.  As a result I'd rate it as a far more useful and relevant test than whiteboard or interview questions.

Unless the job you've got involves spending all day answering theory questions, you need someone who can apply whatever skills they've got.

What you do need to do though is ask yourself was it a fair test of debugging ability - could they run the code, put in break points and so on in the same way they would in the real world?  What sort of error was it?  Is it something the compiler would pick up and flag (in which case it's a pretty pointless question as they'd never need to spot it)?

If it was just written on paper then it's basically just a detailed reading test and that's an even more abstract skill than your average technical interview question and I'd argue, pretty much worthless.

Title: Are debugging skills important to become a good programmer?

Body:
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>


答:
Along with the other qualities should a programmer need good debugging skills?

Yes.

Debugging code is a part of problem solving.  I've never encountered a developer who wrote perfect code and zero bugs.  A developer will be either debugging his/her code, or someone else's.  It's a necessity.

should I consider him for the job?

Maybe, it depends.

Not being able to debug a program in an interview probably shouldn't be a dealbreaker if the applicant was able to complete all other puzzles and programs in the interview.  It really depends on the depth and breath of the interview.

How much debugging does the the position entail?  If a lot, then maybe more weight should be put into how well an applicant can answer the debugging question.  But since you only mentioned that one debugging question was asked, it doesn't seem like it is.


问:
Daily standups- yea or nay?
How valuable (or not) do you think daily stand-up meetings are?

If you're not familiar with it, this refers to a daily meeting that is part of Scrum adherents (and some other agile methodologies).  The idea is that you hold a daily meeting, timeboxed to 15 minutes, and in which everyone must stand (to encourage people to be to-the-point).

In the meeting, you go around the room and each say:
- What you did yesterday
- What you plan to do today
- Any blockers or impediments to your progress.

Do you think this practice has value?  Has anyone worked at a place that's done it, and what did you think?

答:
We had daily standups at my first job. Well, with all the co-ops/interns/temps, it was actually on the long side - usually around 30 minutes.

But the idea of a short, timeboxed, daily meeting helped a lot just to know what other people were stuck on - and if it was something I was working on, I could reprioritize my tasks to finish what they needed to continue sooner. It also gave everyone a chance to know what everyone was working on so if someone had an emergency, everyone was at least aware of what was going on - reducing a truck factor is always a good thing.

Honestly, every day might be a little extreme in some cases. But the idea of short, regular meetings for everyone to stay on the same page is a valuable addition to any process.

Title: Daily standups- yea or nay?


答:
Unless the developer can write clean code all the time (absolutely impossible), and only work on "green field" projects (will never be the case), then yes, debugging skills are absolutely essential.  Absolutely.  I've had experience with developers who just didn't like to debug, so they got lazy, and threw code over the wall to QA for them to test.  But those developers don't last very long at all.

Software development is a craft and a problem solving skill.  Those problems include both the business problems, and problems with their (and other's) code.  By the way, many maintenance projects are specifically about fixing bugs, so debugging is an absolutely essential skill.


答:
Main hiring rule — in any doubt say no.

If you need to implement a lot of new code for cheap — you can get that guy, but personally I would continue searching.


问:
Alternative methods for maintaining JavaScript source
I'm looking for other options for maintaining my personal JavaScript namespace.  The problem I'm having boils down code Organization Vs. Performance.  I would simply LOVE to be able to separate major sections of my code into a more "traditional" style.  But I haven't because if I were to do that I would probably quadruple the amount of HTTP requests I send out.

Essentially I am including two different js files.  jQUery/jQueryUI/my namespace in one and my implementation in the other.  Great for performance in my web-apps... but looking at my JavaScript source makes me scared, confused, and horrified all at the same time.

What am I missing here?

答:
Split the difference.

When developing separate out the source files. You will have a large number of HTTP requests and lots of files.

When deploying compile the source into one JavaScript file.


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
My personal rule of thumb:

Reinventing the wheel is good when you're just learning.  If you have a deadline, you may want to use existing wheels.


问:
How to write a good exception message
I'm currently doing a code review and one of the things I'm noticing are the number of exceptions where the exception message just seems to reiterate where the exception occurred. e.g.

```<code>throw new Exception("BulletListControl: CreateChildControls failed.");
</code>```

All three items in this message I can work out from the rest of the exception. I know the class and method from the stack trace and I know it failed (because I've got an exception).

It got me thinking about what message I put in exception messages. First I create an exception class, if one does not already exist, for the general reason (e.g. PropertyNotFoundException - the why), and then when I throw it the message indicates what went wrong (e.g. "Unable to find property 'IDontExist' on Node 1234" - the what). The where is in the StackTrace. The when may end up in the log (if applicable). The how is for the developer to work out (and fix)

Do you have any other tips for throwing exceptions? Specifically with regard to the creating new types and the exception message.

答:
The things you want to be looking for to "add" to the exception are those elements of data that are not inherent in the exception or the stack trace. Whether those are part of the "message" or need to be attached when logged is an interesting question.

As you've already noted, the exception proably tells you what, the stacktrace probably tells you where but the "why" may be more involved (should be, one would hope) than just going to peer at a line or two and saying "doh! Of course". This is even more true when logging errors in production code - I've all too often been bitten by bad data thats found its way into a live system that doesn't exist in our test systems. Somethig as simple as knowing what the ID is of the record in the database that's causing (or contributing) to the error can save significant amounts of time.

So... Either listed or, for .NET, added to the logged exceptions data collection (c.f. @Plip!):

Parameters (this can get a bit interesting - you can't add to the data collection if it won't serialize and sometimes a single parameter can be surprisingly complex)

The additional data returned by ADO.NET or Linq to SQL or similar (this can also get a bit interesting!).

Whatever else might not be apparent.

Some things, of course, you won't know you need until you don't have them in your initial error report/log. Some things you don't realise you can get until you find you need them.

Title: How to write a good exception message


答:
A good part of programming problem-solving, and to solve a problem you have to know the core-problem not just symptoms or inconsistencies. Debugging is the art of identifying the core-problem.

identify the core-problem

better able to visualize the flow

and many more.


问:
How to keep a team well-trained?
I'm currently mentoring a small team of 4 junior dev in small software company. They are very smart and often achieve their tasks with a high-quality job but I'm sure they still can do better - actually I have exactly the same feeling for myself :) -. Besides some of them are more "junior" than other.

So I would like to find of a funny way to improve their CS skills (design, coding, testing, algorithmic...) in addition to the experience they acquire in their daily work. For instance, I was thinking of setting up weekly sessions, not longer than 2 hours, where we could get together to work on challenging CS exercises. A bit like a coding dojo.

I'm sure the team would enjoy that but is it really a good idea? Would it be efficient in a professional context? They already spend all their week to code so how should I organize that in order for them to get some benefits?

Any feedback welcome !

答: People may well have their own ideas about how they want to learn. Personally I would rather take a course or work on a project in my own time - and have done both. If everyone on the team is OK with the training sessions then go for it, as long as the people on your team will not start to treat it like "work" over time...</p>

Title: How to keep a team well-trained?


问:
Under what circumstances should error messages be presented to the user?
Should error messages ever be presented to an end user and if so what rules or advice should you have about what should be in them?</p>

答:
Error messages should be presented to the user if:

The user initiated the error condition (for example, "you did not include a password on the input form")

The user can do something about the error condition (for example, "there is no network connection")

A critical error has occurred that the application cannot recover from (for example, "the database is corrupt")


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
Too much of anything is never any good.

However, an important thing to bear in mind with "unclean" code is that it can easily lead to "broken windows". If the code is very poorly formatted I think many people new to the code base might feel less inclined to do a good job with maintenance and evolution causing a downward spiral that might eventually affect the working condition of the software.

Therefore maintaining a certain level of cleanliness in the code is beneficial to more than just your fellow developers. Don't spend too much time on it (~5 % has been mentioned). Learn to use the tools of your craft to automate manual tasks (code formatting in this case). Take responsibility for what you do and always do what you feel is most beneficial to your company/customers/users.

Title: Do you actually write 'clean code'?


答:
Errors should be presented to the user when he/she can do something about, along with suggested course of action even if it is to be "call this number" or "click on this link to report the issue".

Never present the user with an error that is meaningless or does not offer a course of action.

Title: Under what circumstances should error messages be presented to the user?

Body: Should error messages ever be presented to an end user and if so what rules or advice should you have about what should be in them?</p>


答:
Yes

Error messages (when needed) should be presented to the user.

What rules or advice should you have about what should be in them?

Present an error to the user when:

What they need to know. Don't include errors that they won't understand. "SQL connection failed" is not a good error. "There was an error saving your appointment." is much better.

They can fix it. "You didn't include a date for your appointment." is a solvable error.

They expect something to happen. Don't fail silently when they are expecting something. Acknowledge the user action at the very least, and at best provide an appropriate error.


答:
I like to be able to tell users if there is a problem with their environment or configuration that is going to stop the software from working and if possible suggest how to address it. You can't always know why you will fail, but environment problems are one of the more common things you run into with PCs.

Users should always know somehow if there is a problem that means they can't do the task they are trying to do. You might not term it in the same way as you would for your own use, but you need to let them know that something has happened. Ideally you want to offer the facility to automatically notify the developer that the problem has occurred as well.

The third situation is if they have made a mistake - left a field empty, put the wrong format of data into a field and so on - that they can rectify for themselves.

The error messages always need to make it clear what has happened and what the user can do to sort it, or what they need to do to make the best of it.


问:
Are there any unions for software developers?
Why does Software Engineering not have union representation like other professional occupations, such as teaching? Are there any unions for software developers that exist and are successful?</p>

答:
I've said this a few times in comments, but I think it merits an answer.

In the UK we do have unions for software engineers/programmers.  The primary one is Unite, which has the primary engineering union as a constituent.  The sector for computing workers is Graphical, Paper, Media & Information Technology.

The union situation in the UK is complex and now relatively few people are union members because of a lot of power being cut from the unions in the 80s, due to anti-union political policies and a few unions setting a bad example, which allowed the mood for changes.

To stay strong, most of the old unions merged together and have continued to do so for some time.  When I was born, most engineers were part of the AEU, the Amalgamated Engineering Union, this merged with the electricians to become the AEEU in 1992.  The AEEU merged with the MSF (Management, Science and Finance) union in 2001 to become Amicus.  UNIFI (Union for the Finance Industry) and the GPMU (Graphics, Paper and Media Union) merged in to Amicus in 2004, and in 2007 the T & G (Transport and General Workers) merged in and the name was changed to Unite.

There is still strong anti-union feeling in the country, particularly from the professional classes, who mistakenly believe that the primary purpose of the union is to bleed companies dry by forcing up wages and striking.  This is not the case.  The primary responsibility of a modern union is to protect their workers from malpractice by their employers.  This is usually in the form of free legal protection for defending members against illegal working practices, unfair/wrongful dismissal cases, health & safety issues, etc.

For the cost of being a member, the ability to get expert lawyers involved for free on your behalf when the ** hits the fan is a life saver.  One of my ex-colleagues is presently taking an old employer to court over unfair dismissal claims.  He was always highly anti-union and is now having to pay out an immense amount of money to take highly disreputable people to court who have huge wallets.  Bet he wishes he had paid the £10.96 a month.

Most professionals, instead of joining "unions", join pseudo-unions in the form of professional membership bodies.  The primary organisation in the UK for programmers is the BCS (The British Computing Society).  Becoming a professional member of this body gives a degree of recognition, requires accreditation via exams, and gives post-nominal letters.  The body also provides many networking opportunities via a wide variety of groups that meet frequently for talks and discussions.  The organisation is also has Royal Charter, so can issue Chartered status to IT professionals, or indeed engineers as they can award the Chartered Engineer status.  I believe there are equivalent organisations in the US and other domains.

Many professions also have regulatory bodies, which are usually compulsory membership and function like unions in part.  Doctors in the UK have to be registered with the General Medical Council (GMC), and are usually members of the medical union, the British Medical Association (BMA).  So it is not only teachers that are professionals and unionised.

To summarise, joining a union is possible for programmers and is highly advisable unless you have total blind faith that your working career will always be free from any potential legal situation.  It is not all about the masses against the classes, it is just common sense to protect yourself and the family that depend upon your job.


答:
Here are some ideas

Book club, read the books like Pragmatic Programmer or other career centric stuff.

Coding Dojo, you can start with a simple problem outside of project and then extend it to the Project or otherwise if you may choose.

Retrospectives or feedback meeting, for getting ideas from the group itself to improve the project development in which every one participates

A user group meeting in which a designated person presents this would improve the presentation/soft skills of the team

once in a while doing a non-work related task like going to Dave & Busters to have a fun friday or sorts.. to improve team chemistry

Any of the tasks or meeting should be less than 45mins just to have the entire group interested. Any thing that goes beyond and hour will completely fall on to the shoulders of the presenter or leader of the group.

Title: How to keep a team well-trained?

Body:
I'm currently mentoring a small team of 4 junior dev in small software company. They are very smart and often achieve their tasks with a high-quality job but I'm sure they still can do better - actually I have exactly the same feeling for myself :) -. Besides some of them are more "junior" than other.

So I would like to find of a funny way to improve their CS skills (design, coding, testing, algorithmic...) in addition to the experience they acquire in their daily work. For instance, I was thinking of setting up weekly sessions, not longer than 2 hours, where we could get together to work on challenging CS exercises. A bit like a coding dojo.

I'm sure the team would enjoy that but is it really a good idea? Would it be efficient in a professional context? They already spend all their week to code so how should I organize that in order for them to get some benefits?

Any feedback welcome !


答:
You should present error messages to the user if he/she can do something about it. Either by allowing sending a bug report before quitting, or by deciding the way to go after a specific kind of error, one that have different possible resolutions that the user knows better the context.

Don't break the user experience if you can/until you have to.


答:
I think it's quite important to show some kind of user-level message when exceptions raices up, this way they have something to report to a supervisor, the dev team could have some more information and bug tracking could be done a lot faster.

The detail on the message should depend on the environment the app is running, from totally verbose in dev env to "There was a problem saving a profile, please contact your supervisor" on a prod env.


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

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

答:
The best FizzBuzz answers I've seen are:

SQL Server 2008

```<code>;WITH mil AS (
 SELECT TOP 100 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil
</code>```

C# (simple)

```<code>foreach (int number in Enumerable.Range(1, 100))
{
    bool isDivisibleBy3 = (number % 3) == 0;
    bool isDivisibleBy5 = (number % 5) == 0;

    if (isDivisibleBy3)
         Console.Write("Fizz");

    if (isDivisibleBy5)
         Console.Write("Buzz");

    if (!isDivisibleBy3 && !isDivisibleBy5)
         Console.Write(number);

    Console.WriteLine();
}
</code>```

C# (clever)

```<code> Enumerable
  .Range(1, 100)
  .Select(i =>
    i % 15 == 0 ? "FizzBuzz" :
    i % 5 == 0 ? "Buzz" :
    i % 3 == 0 ? "Fizz" :
    i.ToString())
  .ToList()
  .ForEach(s => Console.WriteLine(s));
</code>```

Body:
The best FizzBuzz answers I've seen are:

SQL Server 2008

;WITH mil AS (
 SELECT TOP 100 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

C# (simple)

foreach (int number in Enumerable.Range(1, 100))
{
    bool isDivisibleBy3 = (number % 3) == 0;
    bool isDivisibleBy5 = (number % 5) == 0;

    if (isDivisibleBy3)
         Console.Write("Fizz");

    if (isDivisibleBy5)
         Console.Write("Buzz");

    if (!isDivisibleBy3 && !isDivisibleBy5)
         Console.Write(number);

    Console.WriteLine();
}

C# (clever)

 Enumerable
  .Range(1, 100)
  .Select(i =>
    i % 15 == 0 ? "FizzBuzz" :
    i % 5 == 0 ? "Buzz" :
    i % 3 == 0 ? "Fizz" :
    i.ToString())
  .ToList()
  .ForEach(s => Console.WriteLine(s));


答:
I think that the only way to keep a team well-trained is to hire developers that want to continue learning.

If it isn't coming from inside, it won't yield lasting results.

if they do desire to learn, then whether team learning activities are effective or not will depend mainly on interests and learning styles.

Title: How to keep a team well-trained?


答:
I think the dojo system sound cool, and allow them to proceed at home if they want to. Adding some kind of reward could be useful but you might emphasys cometition and i dont think to much of that any good for teamwork.
Anyway, an amazing place to go look for computer problems its Sphere Online Judge. It defines a problem, a set of expected results and lets you upload a file with the solution to the problem. If you get it right, you points go up.

Good luck with that!

Title: How to keep a team well-trained?


问:
Optimizing XML based protocol
We have recently replaced binary based communication protocol with XML one (between browser based client and server). The implementation is almost complete, however I am looking for ways to improve its performance both for faster transmission and parsing. Any ideas ? Please post link along with the answer.</p>

答:
Were I you, I'd avoid premature optimization, and just make sure The Damn Thing Works when deployed to your users. You can optimize later if it's an issue.

Binary for text is an engineering tradeoff. You gave up performance to get portability and human-readableness. Equivalent Exchange and all that. You could just accept the engineering tradeoff and move on to other things.

Keep the binary fat-client implementation around to satisfy the few people who do complain about performance. And when they complain, tell 'em to use the client.

As a last resort, kill all whitespace between tags and shorten tag names. Use default namespaces to avoid extraneous prefixes.

Title: Optimizing XML based protocol


答: I'd keep in mind that there are lots of "interview question"-type web sites, and it's entirely possible to study for a great many questions and puzzles.  One thing you can't study for is debugging code you've never seen before.  Either you've written enough code that you know how to debug or you haven't.  If it's an entry-level position I wouldn't rule the candidate out, but if they claim to have experience with the language and can't debug code in it, it certainly raises a red flag.


问:
Is the ASF going to continue supporting all their java projects in the future?
As you all know ASF quit the JCP and the things between them and Oracle are not going so smooth. Not only that, Oracle is cooking some enterprise level JVMs. With all of these happening, I think it proves that Java is moving to a more closed-source environment. </p>

<p>I'm curious if this will affect all those apache projects built around Java, e.g. Tomcat, Ant, Maven, Derby, Jackrabbit, just to name a few. Will these projects be in danger of disappearing due to the conflicts revolving around Java? Why? </p>

答:
AFS' conflict with Oracle centers on "Field of Use" restrictions that Oracle placed on Technology Compatibility Kits for the Java language.   As I understand it, the TCK's are only licensed for use under the GPL, which effectively bars Apache from a license under their own terms (the Apache license is not GPL compatible).

This is not the first time this battle has been fought.  It was fought in 2007 with Sun as well.  More info here.  As far as I can tell, this issue was never satisfactorily resolved.  But Apache is still around, and all of their software products are still here and being vigorously maintained and enthusiastically used in software projects.

Note that the lack of a license for the TCK does not bar the unrestricted use of the Java language for Apache products, and Oracle offers a TCK that can be used to prove Java compatibility.  Apache merely wants their own, unrestricted implementation of the TCK (called "Harmony").

When the JSR voted to move forward with Java SE 7/8, they did so begrudgingly, and on the technical merits only.  Most of the members are unhappy with Oracle's "Field of Use" restrictions on the TCK.  This kind of thing illustrates why it takes so long for the Java language to get new features.

I don't think the changes to [the
  license agreement for TCK] would have
  any practical difference from what
  they were under Sun's leadership. Sun
  didn't remove the restrictions on the
  TCK and showed no intention of
  changing their mind. The new license
  wording just clarifies what it is that
  they are prohibiting (basically a
  third-party open-source implementation
  of the Java platform).

So this is exactly as it was before,
  only specified more clearly. So, yes,
  the Java SE specification is not
  entirely open, and it never has been.

Somehow, this rebellion broke out only
  after Sun's acquisition. It seems to
  me that the reason is that Oracle just
  seems an annoying organisation (which
  it definitely is), and Larry Ellison
  seems like an annoying guy (which he
  probably is). Also, Oracle is just too
  powerful. IBM and Google like the Java
  leader to be weak. Sun was. Oracle
  isn't. That's the only reason this is
  all happening now.

I don't think this
  affects the Java user community that
  much. We have the OpenJDK, and
  commodity Java products have never
  made much use of Harmony. This only
  affects huge companies that want to
  distribute their own Java platform
  without licensing it from Oracle.

http://www.jroller.com/scolebourne/entry/java_se_7_8_passed#comment-1291735615000

OwnerDisplayName: Mark


问:
How can I transition to a job using the Microsoft stack?
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?

答:
I've successfully made technology jumps more than once in my career.  The first project I worked on was a ColdFusion application (just think of everything wrong with PHP, magnify it, and now you have ColdFusion).  I hated that application, which was driven to loathing when I had to deploy it on a hardened Solaris box.

We had to come up with a tool to do some background processing, which is something ColdFusion definitely wasn't up to the task on.  Since it was a small company, and I wanted to learn Java, I wrote the utility in Java.  I learned a lot about programming in the process.  I also built up my reputation for getting the job done right.

Since Java was object oriented, and I had exposure to C++, was asked to maintain some of that company's C++ applications.  Again a technology shift.

For a while I went back to Java on both the desktop and the server.  That paid my bills for a good long time.  Recently, I had another technology shift to the .Net stack.  The knowledge that I built up regarding application design and problem solving is what landed me the job even though I hadn't written one line of C# code.  C# was similar enough to Java I picked it up to a level where I could be useful while I was waiting on HR paperwork to go through.

At the end of the day, you have to demonstrate that you have technology skills outside the pidgeon-hole where you feel you are now.  That demonstration is most effective with a working application or utility.  The more people who can see that application, the better.  However, as my last transition demonstrates, you don't have to have that application to land a job.  You have to know how to solve problems in a way that's compatible with the company's technology.

When I'm sitting in the interviewer's position, certificates don't really impress me.  The reason is that I have had 50/50 luck with certified developers.  Some were really good, and some were really bad.  There was no appreciable trend either way so it's a non-issue.  What's more important is how well you can understand problems and articulate solutions.


答:
The problem is not with the projects using java (like those you mention), but the projects implementing Java.

The way to be certain you do it correctly is to run the TCK with your implementation and be told what works correctly and what not.  If the Java implementation passes the TCK correctly, it can be called Java-compatible.  If it doesn't it cannot.

Problem is that the intent for others to be able to implement the Java Language Specification cannot be verified unless they have a license to the TCK.  Apache has asked for a TCK license for free, but this has silently been denied by first Sun and then Oracle.  This is most likely because the engineers who knew that the best way to make software is to help each others worked towards Open Source, but the decision makers have denied for the potentially money making technologies to be opened up.

What all this means is - in MY opinion - that it has finally been clearly shown without any doubt that Java is a proprietary Oracle technology, and not a free open source technology.  This does not imply any changes for the libraries under the Apache umbrella, unless if Apache itself decides to boycott Java which I belive is very unlikely, only for the Apache Harmony Java implementation.

Title: Is the ASF going to continue supporting all their java projects in the future?

Body:
As you all know ASF quit the JCP and the things between them and Oracle are not going so smooth. Not only that, Oracle is cooking some enterprise level JVMs. With all of these happening, I think it proves that Java is moving to a more closed-source environment. </p>

<p>I'm curious if this will affect all those apache projects built around Java, e.g. Tomcat, Ant, Maven, Derby, Jackrabbit, just to name a few. Will these projects be in danger of disappearing due to the conflicts revolving around Java? Why? </p>


答:
The major difference I've seen between junior programmers and senior programmers is their skill at debugging. Skill at debugging is something that only comes with practice and experience.

For example, think of a strange bug where a Java program works fine on the console in interactive mode, but fails when you try to use a Unix pipe for the same input. If you've encountered this problem before, you might check to be sure that new Scanner(System.in) is only called once; the bug being that it consumes the buffer when piped, but obviously not when in interactive mode. I would expect a more senior programmer to identify this bug faster. Perhaps because they've experienced it before, or because they've had other issues with buffering in the past.

As for puzzle solving and writing new code, while experience is important, this is something where a junior-level programmer can perhaps perform just as well as, or even better than, a more senior programmer. That is, intelligence and skill can have a larger effect, which is independent of experience.

If you are in a position to invest in a junior programmer, who may have new ideas and can help the team "gel," and they seem fine writing new code, go ahead and hire them. If you are looking for a senior-level programmer, then this lack of debugging skill may be a major warning sign: They might have ten years experience that only amounts to experiencing the first-year ten times.

As a side note, there are ways to become better at debugging without having 10 years of experience first. I recommend Andres Zeller's book Why Programs Fail: A Guide to Systematic Debugging as a way to learn scientific principles and to better understand how to reproduce, find, and fix failures.


答:
I think what Apache is doing is waiting for the community to pick up on OpenJDK - they want that to be the future of Java instead of Oracle. This is a very mature decision from Apache and I really respect them for this.

Java is just a language. It's silly for Apache to change languages because they're having issues with one implementation they were using (Oracle's).

So yes, they will definitely continue writing things in Java, and I'm pretty sure OpenJDK will be the next big thing for them.

Here's a quote from Jim Jagielski (Co-Founder, Chairman, Apache Software Foundation) on his blog-post about JCP's death and a new future that should be driven by the community:

But maybe, from this death, a new,
  true community process might arise
  somewhere, with a different collection
  of people, one with no entity "more
  equal than others". That is something
  I think the ASF would be quite
  interested in seeing.

It's great to see these kind of radical changes happening in software. I wish they would happen in the government system as well, because sometimes things need to change.


答:
It depends on your environment. If you play sodoku and other puzzles all day, perhaps it would be a good candidate.

If however, you sometimes have bugs in your code, or it doesn't always perform exactly as expected I suggest you get someone good at troubleshooting.

Hire for what you need, not some ideal of what a programmer should be.


答:
There's a number of skills we need as developers that aren't necessarily directly related to code.  One example is presenting, and explaining technical things to non-technical people in a way they can understand.  Something that can be effective while you are getting your team up to where you want them is to give something like homework.

Each week, you give your guys a problem to work through.  To keep it most beneficial to the company keep the problems to something relevant to what you are working on.  Preferably some pain point you haven't figured out the solution to yourself yet.  Each of your junior members would take turns presenting (preferably one a week) while you play the role of the client.  Essentially, you have two goals with this approach:

The act of teaching/presenting requires the guy on the floor to have a deeper knowledge than just doing exercises.  It's an indirect, yet very effective way to teach someone a topic.

If they can convince you that it is a good idea, they might be able to convince a client the same thing.  Make sure you throw in questions that make them think about the business impact of what they are proposing.

Of course, start each session with a reminder that you are going to ask pointed questions--and the purpose is not to be mean, but to prepare them for a tough client.

Title: How to keep a team well-trained?


问:
DVCS and different versions of the same Product
Let's say that we have an application, with two (or more) different versions. E.g. Professional and Lite editions.

What would be the best way to keep the source under version control (DVCS in particular). The assumption here is that some or most of the code is common, but the Professional edition has some extra code as well.

What would be the optimum way of versioning the code with a system like git or Mercurial?

答:
Use the modularity of your language to organize a software product line, rather than the version control system. Quite simply, the merge process is not something you want to be a regular part of building your products. Rather, the design of your product should already take this into account.

By accounting for the software product family at the design level, this will also make it much clearer to developers what the variation points are: the variation points will be obvious in the design, rather than implied as source code differences.

This will ease developer testing as well: Any modifications you make should be tested on both products. You won't want to be making the same change twice, or constantly merging and undoing changes as they occur.

Review the literature on software product lines to see the best practices for your language. Using these techniques, you can create a third "product" that is streamlined for testing. For example, using dependency injection can be your mechanism for both testing and for having variants of the same program.


答:
Yes, errors should be reported. Consider the situation where the user inputs the wrong password and was bot able to log in. Imagine what if the application instead of giving error, "Wrong password or username" simply gets back to the original password asking screen. The user will certainly get confused saying "Huh.., what did just happen?".<br>
Report every possible error that can occur and which the user can understand. Also think about what the information should be displayed. Think about the support. If the user after getting error, comes back asking why the error, then the support should be able to answer. For this there should be enough information in the error. This information need not be shown to the user, but must be somewhere in the logs. </p>

Body:
Yes, errors should be reported. Consider the situation where the user inputs the wrong password and was bot able to log in. Imagine what if the application instead of giving error, "Wrong password or username" simply gets back to the original password asking screen. The user will certainly get confused saying "Huh.., what did just happen?".

Report every possible error that can occur and which the user can understand. Also think about what the information should be displayed. Think about the support. If the user after getting error, comes back asking why the error, then the support should be able to answer. For this there should be enough information in the error. This information need not be shown to the user, but must be somewhere in the logs.


答:
You should always present a problem to a user in easily understandable words based on information provided by the underlying architecture.

"The file could not be saved to this location.  You must save it to another location".

You should also allow for the user to access the full error messages and forward them to the development team, but do not do it up front.  This can be very helpful in a phone support situation.


问:
How important are daily builds?
One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?</p>

答:
I think what's important to note here is that regular builds help catch errors sooner rather than later. It doesn't have to be daily, but often enough. Ideally, it can also run your unit tests.

The goal is to find out when a build breaks before the final testing phase, to find them as soon as possible.

Just set it up to build your main development branch(es).

We use it at work (although we build hourly), and often when we forget to set-it up we find about problems just hours before releasing.

Title: How important are daily builds?


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
My general rule is that a function should fit on the screen.  There are only three cases I have found that tend to violate this:

1)  Dispatch functions.  In the old days these were common but most of them are replaced with object inheritance these days.  Objects only work inside your program, though, and thus you'll still see occasional dispatch functions when dealing with data arriving from elsewhere.

2)  Functions that do a whole bunch of steps to accomplish a goal and where the steps lack a good subdivision.  You end up with a function that simply calls a long list of other functions in order.

3)  Like #2 but where the individual steps are so small that they are simply inlined rather than called separately.


答:
My advice, code-wise, is to never swallow errors/exceptions, and never catch general exceptions. Catch only specific ones that you know are possible (for example, array "out of bounds" errors) and handle them accordingly, giving the user some type of feedback as per @Josh K's answer.

However, there are times where it's probably better to swallow errors. Something stupid like a user opens a file used by your app and prematurely kills the program, causing some type of file handling error -- your application is closing, it offers no benefit to deal with it. In this case, you still shouldn't just ignore it, just dump the problem to an error log and if the user has a problem, you can refer to that.

That's also another point: record your application's errors with an error log. Fairly simple to do and could save you dozens of headaches in the future. Just take precautions to make sure it doesn't balloon up to 20 GB in size.


问:
Does music increase your productivity?
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)

答: I started listening to Soma.fm. They have some stations with easy-going, lounge kind of music. It doesn't distract but keeps you going.</p>

Title: Does music increase your productivity?


答: Reinventing the wheel is a great way to learn how a wheel works, but it is not a good way to build a car.</p>

Title: Is reinventing the wheel really all that bad?

Body:
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?


答:
Since you already have PHP experience many of the web development skills you acquired will be of great use, if you move asp.net web development. I personally prefer asp.net mvc because it is more structured and Microsoft almost recommends it over Web Forms. So your CSS, JavaScript and HTML etc skills will not be lost in this transition.

I would recommend certification, with a word of caution that a certification does not entitle you with any thing. But, it would be a proof that you have understanding of asp.net/microsoft stack. You can easily justify your job search in microsoft technologies. On the top, a Certification preparation will expose lot of concepts to you. Getting a certification is better than sitting and biting nails, unless you have a interesting pet project in asp.net or anyother tool in microsoft stack.

If you are employed by a company they do expect you to be productive the level varies but the whole idea is now how proficient are you in Microsoft stack? I personally like www.tekpub.com  for lot of good screen casts and the good work of Rob Conrey, for dissecting things into simple understandable units of tutorials. This would expediate your learning process. I would strongly recommend that even though it has a monthly membership which is nominal if you live in OECD nations.

Got to amazon and chase the books on asp.net/microsoft.net typically choose a book with 5-star rating and commit yourself. Last but not the least, learn to install all the required software Visual Studio, SQL Server and other things required on your personal computer (express edition should be fine). Do that by yourself, either by searching internet or a book. This is very important skill, that would be handy and simple in most cases, but there are some lessons that can be learned there.

At least ensure you have implemented that little shopping cart or blog-engine mini-project to see how the whole thing falls into place.

Title: How can I transition to a job using the Microsoft stack?

Body:
I graduated from university with a computer science degree (BSc), having done some C, C++, Java, Python, and Oracle along the way. I did some freelancing while I was at university and carried this into a full time job when I graduated, and I've been working full time for a year now.

PHP isn't really what I want to do, and I think it's limiting my opportunities the longer I stay along this path. It's not a language I like to use on a daily basis, and I would like to work in a larger organization, where it doesn't seem PHP has much use.

I want to stay in web development, and there seems to be plenty of jobs for the Microsoft stack: C#, SQL Server, and ASP.NET MVC. But beyond a half semester writing common-line C++ in Visual Studio, I have no experience with Microsoft technology.

Where do I start to make the transition to landing a job in a Microsoft shop? Are there any specific certifications I should be focusing on, or university courses I should be taking? What are employers or recruiters looking for?

What can I do besides creating a pet project in my spare time?


问:
What are you telling yourself if you can't understand new concept, paradigm, feature ...?
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?

答: Personally, everything is an analogy away. And if I don't understand something, it's probably because I haven't been shown the right concept to bridge me over to the Land of Understand. I usually keep scouring around for different tutorials and eventually one of them will take a different turn than the previous tutorials did that I didn't grok. Then I'll go back and read all of them and finally piece it together. And then rage why the other tutorials didn't present it the same way.</p>


答:
That simply means you still don't have enough experience in that one specific area. As we acquire experience we start mapping concepts from other areas which helps us understand the new concepts faster.
Don't beat yourself over it. Just keep pushing, ask a friend, etc... You're learning and that is a great.</p>

Title: What are you telling yourself if you can't understand new concept, paradigm, feature ...?

Body:
Programming always required to learn new concepts, paradigms, features and technologies and I always have been failed at first attempt to understand new concept what i encounter. I start to blame and humiliate myself without remember before how i understood new concept which i hadn't understand it before.

I can hardly stop to tell myself "why i cant understand ? Am i stupid or idiot ? Yes, i am stuppiiddddd!!!"

What your inner voice tells if you can not understand new concept after spend long time till been tired or hopeless ?

How do you handle your self-esteem in such situations ?


答:
Well, his own method being as efficient as framework would be pretty rare because most frameworks still have bugs and no framework can give you an out of the box solution. Most programmers who can't think will never try to write anything at the framework level; they will just search Google for a ready-made solution. Any wise programmer will first see if there is a free framework that has the functionality he needs, and then write the solution himself if there isn't. Sometimes it is way too difficult to explain the current project situtation and the developer is the best judge. </p>

<p>Reinventing the wheel is not bad, it is a statement made by lazy people to avoid working hard. Even framework writers do reinvent; the entire .Net framework was reinvented to do what COM was offering. </p>

Body:
Well, his own method being as efficient as framework would be pretty rare because most frameworks still have bugs and no framework can give you an out of the box solution. Most programmers who can't think will never try to write anything at the framework level; they will just search Google for a ready-made solution. Any wise programmer will first see if there is a free framework that has the functionality he needs, and then write the solution himself if there isn't. Sometimes it is way too difficult to explain the current project situtation and the developer is the best judge.

Reinventing the wheel is not bad, it is a statement made by lazy people to avoid working hard. Even framework writers do reinvent; the entire .Net framework was reinvented to do what COM was offering.


问:
Why is free software good for programmers?
When I say Free Software I mean it in the FSF terms. Free as in Free Speech, not as in Free Beer.

Why is it a good idea for programmers to use and write Free Software?

答:
I think that open source is good for programmers.

With open source a programmer can learn from the work of other programmers and have a better debugging session (e.g if the library/framework/API is open source).

The only additional benefit of free software for a programmer is the reuse of existing code, but this benefit is not actually for the programmer, but for the programmers' company.


答:
Prelude

Well, my boss just just plugged in two servers on the other side of an un-insulated drywall wall, and there are 4 more to turn on. Right now, I'm glad I bought a pair of noise canceling headphones.

Ideally I think programmers should be setup into teams that work in private rooms.  This gives us a quiet environment that can help us concentrate, and fellow programmers that we can talk through an issue with without distracting other programmers whom are not concerned with the issue.  Alas that is an ideal world though.

Answer

As per the exact question, I use noise canceling headphones with music when I'm not working through anything particularly complicated.  If I really need to focus however, I turn the music off and just let the noise-canceling effect do it's job. Gives me a reasonably quite atmosphere to think.

Also, I've read that there have been studies that show that music without lyrics is far less distracting than music with them. This might be something that some people would like to explore.

In Closing

I think whether you listen to music or not, a decent pair of electronic noise canceling headphones are one of the best investments you could ever make.  They are more comfortable, as well as more manageable than earplugs.

Title: Does music increase your productivity?

Body:
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)


问:
What's the best way to run a technical book club?
At work, we've been doing lunchtime book clubs for a while. So far we've done:

Clean Code

Working Effectively with Legacy Code

The Pragmatic Programmer

We read a chapter per week, and one person is assigned to present over the content and help facilitate discussion.  Of the three, we've probably had the most success with The Pragmatic Programmer. It seems like the more technically complicated the content was, the more people tended to drop out as the book went along.

I'd like to do a technically-heavy book like SICP or Java Concurrency in Practice, but I don't know of good ways to make this work with the format we're currently doing. What advice do you have?

答: My personal take on technical heavy books is daily discussion. I understand from a bookclub standpoint that is difficult, but how about making your group take the challenge of acing a certification exam. Having it confined to say 4 weeks of prep, that is the fun of engaging in technical stuff. In that case you would not need an entire village, the group end up with a handful of motivated people and would really filter itself out in a week. Trust me, this is how you can challenge yourself and the team.</p>


答:
I prefer either white noise - such as the 'music' of servers humming in the background - or a consistent level of talk, from either radio or TV.

I dont like programming or working with music in the background.

Title: Does music increase your productivity?


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
In general, I avoid reinventing the wheel if the functionality I desire, or something approximating it, exists in the standard library of the language I use.

However, if I have to incorporate third party libraries, it's a judgment call depending on how widely used and esteemed the library is.  I mean, are we talking about Boost or Bob's Kick-ass String-Parsing Tools 1.0?

Even if the library is generally well-known and highly-esteemed throughout the industry, it's still a third-party dependency.  Programmers generally place significant emphasis on the virtues of code reuse, while often glossing over the danger of dependencies.  A project with too many third-party dependencies is likely to fall apart in the long run as it slowly devolves into a maintenance nightmare.

So leveraging existing code is good - but dependencies are bad.  Unfortunately, these two statements are at odds with each other, so the trick is trying to find the right balance.  That's why you need to identify acceptable dependencies.  As I said, anything in the Standard Library of the language is most likely an acceptable dependency.  Moving on from there, libraries which are highly regarded throughout the industry are also generally acceptable (like Boost for C++, or jQuery for Javascript) - but they are still less desirable than the Standard Library because they do tend to be less stable than standardized libraries.

As for libraries which are relatively unknown, (e.g. the latest upload on SourceForge) these are extremely risky dependencies, and I would generally recommend avoiding these in production code, unless you are familiar enough with the source code to maintain them yourself.

So it's really all a balancing act.  But the point is that just blindly saying "Code reuse good! Reinventing wheel bad!" is a dangerous attitude.  The benefits of leveraging third-party code must be weighed against the disadvantages of introducing dependencies.


答:
Of course reinventing the wheel on a whim, out of ignorance and arrogance can be a bad thing, but IMHO the pendulum has swung too far.  There's a tremendous advantage to having a wheel that does exactly what you want and nothing more.

Often when I look at an existing wheel, it either does way more than I need it to, suffers from the inner platform effect, and is thus unnecessarily complex, or it is missing some key feature that I do need and that would be difficult to implement on top of what's already there.

Furthermore, using existing wheels often adds constraints to my project that I don't want.  For example:

The existing wheel requires a different language and/or programming style than I would otherwise prefer to use.

The existing wheel only works with the legacy version of a language (for example, Python 2 instead of Python 3).

Where there are tradeoffs between efficiency, flexibility and simplicity the existing wheel makes choices that are suboptimal for my use case.  (I've been known to reinvent even functionality from libraries that I originally wrote myself in these cases.  Usually it's because I wrote the library version of the function to be generic and reasonably efficient, when I currently need something that's very fast in my specific case.)

The existing wheel has tons of legacy cruft that's totally useless in the case of new code but makes life difficult nonetheless (for example, a Java library I use that forces me to use its crappy container classes because it was written before generics, etc.).

The way the existing wheel models the problem is completely different than what's convenient for my use case.  (For example, maybe it's convenient for me to have a directed graph represented by node objects and references but the existing wheel uses an adjacency matrix or vice-versa.  Maybe it's convenient for me to lay my data out in column major order, but the existing wheel insists on row major or vice-versa.)

The library adds a massive, brittle dependency that would be a major hassle to get up and running everywhere I want to deploy my code, when all I need is a small subset of its features.  On the other hand, in this case I sometimes just extract the feature I want into a new, smaller library or just copy/paste if the library is open source and the codebase makes doing so sufficiently simple.  (I've even done this with relatively large libraries I've written myself, not just other people's.)

The existing wheel attempts to be pedantically compliant with some standard that is both inconvenient and irrelevant for my use case.


答:
If you don't understand a problem, there is an easier problem that you don't understand.

Find that problem, and solve it.  Then try your original problem again, and see if you are ready for it.


问:
Are debugging skills important to become a good programmer?
Along with the other qualities should a programmer need good debugging skills? If I have an applicant who was not able to find the error in the given program, but was able to solve all puzzles and programs, should I consider him for the job? </p>

<p>EDIT :- The puzzles are normal red,blue and red-blue balls like. The programs are like  finding continuous k zeros in an array. The debugging program is something which fails because of condition which should be >=, but instead is >. Everything is on paper. </p>

答:
should a programmer need good debugging skills?

Yes. That said, I would ask you to consider the methodology in the interview (i.e. quiz / test-style) less than perfect (okay, flawed) in that many people find code on paper a strange, unfamiliar experience.

Since debugging is a process, not the answer or result (e.g. the mistake), I would suggest using an interactive dialogue or discussion as a better means for assessing a candidates debugging abilities. While most people use an informal ad hoc system of debugging, good candidates will have a similar pattern in general, of asking questions to gain understanding the system or assumptions, and requirements, then isolate the problem (often divide and conquer), and methodically compare the code to the requirements, and evaluate expected input/output, rather than a willy-nilly changing a bunch of things at once haphazardly until it works.

I also express reservations about puzzle problems during interviews, particularly in written form, as if the candidate doesn't have the right assumptions of framework of reference (the trick), the puzzle maybe unsolvable to them. I.e. Many interview puzzles suffer from having a single correct path, whereas life is complicated and the most creative thinkings are the ones who take surprisingly novel approaches to solve a problem that may not worked with a given particular pre-cooked puzzle, with an expected solution. It's like expecting all trumpet players to play jazz. This can be managed by asking the question as a non-confrontational (pressure can confound creativity) interactive discussion. Again, to me, the answer is secondary to see a good thought process being expressed. You will likely need to ask them to think out loud, but this tends to be more productive in my experience.

I haven't read or evaluated Zeller's Why Programs Fail, but I can recommend Debugging by Agans as a short, quick read that can help solidify the ad-hoc debugging process into a more structured, concrete, and organized effort, which can help to be more efficient at debugging. Also print out a copy, and hang it at your cubicle or workaround, the Debugging Rules poster, it's a perfect reminder for those bad days where nothing seems to go right. I have few bad days, and spend less time actively debugging (read: scratching my head in confusion) by trying to follow them in spirit if not in letter.


问:
Is recursive-descent parsing a panacea for DoS threats posed by 'Evil' regexes? Or does evilness stem from the grammar?
ReDos attacks exploit characteristics of some (otherwise useful) regular expressions ... essentially causing an explosion of possible paths through the graph defined by the NFA.

So does using a recursive-descent parser (such as ANTLR) necessarily avoid the problem?

答:
Necessarily? No.

Recursive decent parsers can be implemented just as naively as the regular expression algorithm (you could implement the NFA via recursive decent for example). They're arguably more likely to have the problem because they usually have to deal with context free grammars, which allow a wider range of complexity and thus a wider range of possible exploitable use.


问:
Are there any arguments that can make a contractor reconsider working on fixed price?
I've been working for a contractor who brings in some good projects, but they are all fixed-price and often fixed-time.

As a result he always has me making a quote over loose requirements, which never fails to bring a lot of tension due to feature creep.

He claims he'd never get a contract if he couldn't agree on a price with his clients first, but as far as I'm concerned I don't wanna go through another project under these terms.

Is there any argument I could make to have him pay me by the hour, or should I just suck less at estimating ?

答: The problem here is not the fixed price of project - it's the loose requirements. If you can pressure him to give you a more firmly defined spec, your time estimation will get better.</p>


问:
Alternatives to cron jobs or other ways of improving scheduled task performance
I'm working on a social networking website where users gain ratings after specific actions taken and proper conditions are met on the tables. The ratings are calculated depending on 'total hours worked' and 'total points gained'. The cron php has an sql that INNER JOINs 7 tables. To keep this up-to-date we run a cron to check the table entries once a day to update values.

This is just one cron of 15 in total. Some of them only sends emails with Mandrill, one sends a newsletter and there will be more newsletter in near future.

Currently, when there is an active event on the site (it's kind of an event networking site but with administration and onsite management features), around 2000+ users and their data are involved in these processes. But there will be more and more soon.

We had two server crashes that really ruined the server because of two crons before, one of them is the one which updates user ratings. The second cron that was having problems was updating the total hours a user worked in two tables. We will need to have even more scheduled tasks for other data like these to be updated automatically.

After some research I've found The Fat Controller which is -

A parallel execution handler, used to repeatedly run other programs, usually scripts, a bit like CRON. It was designed to handle the execution of scripts which perform background processing for websites which generally need to repeat, react to how much work there is to do at any one time or run as a daemon.

(As stated here - http://fat-controller.sourceforge.net/index.html )

Any ideas on how the performance of running 5 php scripts previously used as cron jobs would be compared to running them as cron jobs? Also, some of the cron jobs we currently have need to run in specified hours/days (i.e send mail to a user - not weekend - at 9.30 etc.) is this possible with a tool like the fat controller? Or is it possible to set the task to run once a year?

Any recommendations on the best way to handle this kind of processes would be really appreciated.

答:
I run a Rails server that has to handle quite a lot of background processing. We use different approaches depending on the job wee need to do and the amount of processing they take or how we need to schedule them.

To start, your jobs should be able to run concurrently. That's basically seeing every job as a user and making sure to use the same technics you would use for multiple users like transactions and record locking.

Basically there are three approaches:

Simple cron jobs. We use this for jobs that run very regular (every hour, once a day) and that need A lot of processing (for some weird reason running a Rails script from the command line and the same script inside aRails controller the latter case sometimes uses much more memory, also runs a bit slower)

The second approach is what you call the 'fat controller'. This controller is called by a cron job (just running a simple curl or wget from cron.hourly). That's for some simple tasks where we run things at a specific time, or maybe only if other jobs do not run. (I use a simple trick here, when the controller starts it will write a temporary file and deletes it when finished, if the file is present at startup it will not run at all, avoiding some conflicts if some data import takes longer than expected).

Third variant is a quequ. Basically a table where I write some requests that can be performed later or at night (sending emails, converting images...). Another cron job will then start to work on this queue at a given time. (There are several nice libraries for Rails that help organizing this kind of work.)