问:
How to teach basic principles to programmers
In order to get experience as a team lead, I was recently given the task of supervising a programmer.

What I found out is that he is having a problem in writing a simple if condition. He has issues with string. And he doesn't know how to pass a variable in the addClass function of jQuery with an if condition.

And he doesn't know when to use a for loop. Or even what a for loop is used for.

How to make him understand these basic concepts quickly?

I told him to Google for how to use if condition for addClass variable. But he didn't find it, then I told him to do it quickly in the early morning, when discussing he was giving reasons that it is what that, then I told him I show you how to do that,
then he told me, you should have done it before.

What should I reply to him? He is telling me that you should tell me everything or Should I do it and show him every time? It may take lot of time, and every time I have to do a task. I want him to be independent.

答:
Assuming that you really want to help him learn on the job and you won't/can't fire him due to complicated reasons best known to yourself (e.g. politics such he is the CEO's son) as the issues mentioned are really basics that even a student with 1 semester of programming experience should know. I suggest the following:

Arrange a meeting with your superior to let him know that he is simply not yet suitable for a basic job as a programmer. If he insist you should continue to work with him, proceed to step 2.

Be honest with him and point him to websites such as http://www.codecademy.com/ or less dry introductions to programming such as 'Head First Java' and get him to struggle himself. Tell him that these resources hold the answers to his questions and that although you like to help, you are really busy during this period. Close off methods for easy contact or he will get reliant on you. Act really busy!

Track his progress by making it compulsory for him to submit a daily and weekly report of his learning at the end of each working day and provide your feedback once a week to see if he is going off track and to show that you are trying to make some time for him as well.

When you feel he has gotten the minimum basics, you may start to gently introduce him to small real tasks as weekly homework.

In other words, treat him like a beginning student, for he is at such a level. If he decides to quit, I believe you have done what you can as well. Meanwhile I'm afraid you would have to do his work or get an extra helper if possible to ship things on time.


问:
How should repetitive calendar tasks be stored in the database?
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?

答:
Repeated tasks should have a start date and an end date. For a single date task they would be the same date.

Create some sort of "Dates" table that has one record for every day you think is relevant from the start of your needs as far into the future as you want: 12/31/2100 for example and convert to your format.

A query might look like:

```<code>Select
  t.id
  , t.label
  , d.UnixDate
from Tasks as t
inner join Dates as d
on d.UnixDate >= t.StartDate
  and d.UnixDate <= t.EndDate
where t.id = [ID Param]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Repeated tasks should have a start date and an end date. For a single date task they would be the same date.

Create some sort of "Dates" table that has one record for every day you think is relevant from the start of your needs as far into the future as you want: 12/31/2100 for example and convert to your format.

A query might look like:

Select
  t.id
  , t.label
  , d.UnixDate
from Tasks as t
inner join Dates as d
on d.UnixDate >= t.StartDate
  and d.UnixDate <= t.EndDate
where t.id = [ID Param]


答:
Perhaps the person was assigned to you by someone who wanted to get him off their team. Beware of other teams who want to give you a person.

But if you are stuck with him then find some online how-to-program courses like MIT Opencourseware and tell him to work through it.

Or assign him to help desk/telephone tech support.

Meanwhile tell the managers if they want their project done on time to find someone else.

Title: How to teach basic principles to programmers

Body:
In order to get experience as a team lead, I was recently given the task of supervising a programmer.

What I found out is that he is having a problem in writing a simple if condition. He has issues with string. And he doesn't know how to pass a variable in the addClass function of jQuery with an if condition.

And he doesn't know when to use a for loop. Or even what a for loop is used for.

How to make him understand these basic concepts quickly?

I told him to Google for how to use if condition for addClass variable. But he didn't find it, then I told him to do it quickly in the early morning, when discussing he was giving reasons that it is what that, then I told him I show you how to do that,
then he told me, you should have done it before.

What should I reply to him? He is telling me that you should tell me everything or Should I do it and show him every time? It may take lot of time, and every time I have to do a task. I want him to be independent.


答: I have done something similar years ago implementing an interface like Windows Task Scheduler and basically for each task you have StartDate, EndDate (can be null), StartTime and RecurringDays that contains days of week when the task must be scheduled.</p>

Title: How should repetitive calendar tasks be stored in the database?

Body:
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?


答:
If this is a personal project and you just want a way to store your tasks, I recommend TaskCoach. It's a desktop application, multi-platform, open source, easy to get started and have really good features.

In case you are developing a task application, then the most probable way is to add a new row for each recurring task. The logic is that each task is a separate entity in itself and it must be completed before the same task is to be started the next day. If you just increment it, you just can't capture the history of the task.

In case you feel, that it would just give you a big list if a few tasks weren't completed then you could trigger an event once the recurring task is completed so that the new task gets generated as a new row only when the task is marked as completed. As suggested by Morons you could use a separate table with a flag for recurring tasks in the original table together with data for recurrence (days,weeks,recur time) so that you could just have a simple script that could generate the recurring tasks based on date or a condition or by label.

But if you are sure that the task is a surely repetitive one without any change(such as brush daily) and doesn't need extensive tracking, then you could just try the following structure

Recurrence flag - to indicate that the task is recurring

Recur period  - day, week, month

Number of tasks created - This would increment the task based on the recur period. So if the task starts today and has a recur period of one day, it would just increment by one tomorrow

Number of tasks completed - This would increment if the task gets completed

The logic is the difference between tasks completed and tasks created should always be the recur period if the task is always completed. So dividing the difference of days by recur period would give you an indication of how long has the task been pending.

Thanks for Kareem for pointing this out

IMHO, task applications are difficult to build for people at large.


答:
In my view there are two options:

Store a large amount of equal rows for reoccurring items, however they have to end (either through a end date, or a finite number of items), and have to be marked as a reoccurring item. When you change the event, you have to update them all, but when you want to deviate once, you can simply 'break' the connection between one event, and make it a normal event.

Store the event as a reoccurring item, with a certain repetition scheme, and compute for a given date which reoccurring items are due on the given date. This gives the possibility for infinite repetition.


问:
typedefs and #defines
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.

Consider the below 2 situations to use int data type with another name:

```<code>typedef int MYINTEGER
</code>```

and

```<code>#define MYINTEGER int
</code>```

Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.

Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).

答:
"#define" will replace what you wrote after, typedef will create type. So if you want to have custome type - use typedef.
If you need macros - use define.</p>

Title: typedefs and #defines


问:
What do you think of this new if-then syntax
I was just thinking of something that would be really cool to have in my if-elif-else controls.

```<code>
if condition:
    stuff()
elif condition:
    otherstuff()
then:
    stuff_that_applies_to_both()
else:
    stuff_that_doesnt_aply_to_either()
</code>```

So basically a then will be run when any of the conditions are run EXCEPT the else condition. Do you think this is useful? It's similar to the try-except-else of python.

I think some of you are nitpicking a very preliminary implementation. The then block would be just like the else block in a try-except block in python. The real reason I suggest this is for situations like this.

```<code>
m = {}
if condition == '1':
    m['condition'] = condition
elif condition2 == '3':
    m['condition2'] = condition2
elif condition3 == 'False':
    m['condition3'] = True
then:
    run_test_that_relies_on_one_of_the_conditions_being_true()

return m
</code>```

The then block is scoped to the first if just like the else is. So nesting works fine. And if you need to run a method before the if statements, that really has nothing to do with this use case.

答:
I wouldn't mind using something like this myself today. But, to be sure I'd use it about as often as I use repeat until.

Code would at least look better without the superfluous nesting. Although I prefer Else If to elif.  I'd replace the Then with Do and the final Else with Otherwise.

ContentLicense: CC BY-SA 2.5


问:
Should I pass an object into a constructor, or instantiate in class?
Consider these two examples:

Passing an object to a constructor

```<code>class ExampleA
{
  private $config;
  public function __construct($config)
  {
     $this->config = $config;
  }
}
$config = new Config;
$exampleA = new ExampleA($config);
</code>```

Instantiating a class

```<code>class ExampleB
{
  private $config;
  public function __construct()
  {
     $this->config = new Config;
  }
}
$exampleA = new ExampleA();
</code>```

Which is the correct way to handle adding an object as a property? When should I use one over the other? Does unit testing affect what I should use?

答:
I think the first one will give you the ability to create a config object elsewhere and pass it to ExampleA. If you need Dependency Injection, this can be a good thing because you can ensure that all intances share the same object.

On the other hand, maybe your ExampleA requires a new and clean config object so there could be cases where the second example is more appropriate, such as cases where each instance could potentially have a different configuration.


问:
How early is too early to be involved in new feature development?
I develop an internal business application that our engineers use to test and debug the company's product. The engineering manager has been pushing to get the software developers involved when the engineers are in their design phase. He says that he wants to give us an idea of what's coming down the pipe, and give us the opportunity to provide feedback on their designs (we rarely have feedback).

The engineering manager wants the developers and engineers to implement new features simultaneously, so that by the time the engineers have implemented their end, they can use the software to test them. The feature designs tend to be volatile until they are fully implemented by the engineers, making it difficult to draw up requirements. He thinks the engineers and developers can do all of our debugging side-by-side, at integration time.

It all seems inefficient and backwards to me.

答:
Ideally it should work this way but this assumes an agreed upon design that doesn't change rapidly during the implementation phase, and that would go for both the engineering disciplines in this case, not just the software related one.  They are dependent upon each other in this case.

The situation seems as if the engineers do not have a full grasp of the problem they are trying to solve before designing, or they problem they are trying to solve is well established but they are just not sure how to solve it until they get their hands dirty.

This forum doesn't pertain to non-software related engineering disciplines, however if this were a software design problem, the best way to mitigate this kind of problem is to have the developers begin developing a rough prototype that aims to address as many potential unknowns in the formal design as possible.  This way, the formal design can be more complete and the problem's implementation approach can be highly understood.


答:
There's no general rule, it's always a tradeoff.

On the one hand, involving SW engineers early may mean a lot of wasted work for them, because they discuss and think about problems that turn out to be irrelevant.

On the other hand, involving SW engineers early allows them to give feedback about the relative complexity of the desired functionality, and about possible problems. This may save the other engineers a lot of time, because they can change their plans early to avoid problems later when the software is being developed.

At what point exactly to involve SW devs depends on how you want to make that tradeoff (e.g. how likely is it that engineering will make design decisions that later make life hard for the SW devs; how likely is it that SW devs can help the engineers; how important is it to minimize risk in the project, even if it means higher overall cost).

That is very much a project-specific decision (and a difficult one).

Edit

The question really boils down to "Should SW devs be involved in the requirements design?". In my experience, some (limited) involvement is very valuable even early on, as it avoids totally unrealistic requirements.

Basically, requirements design is about "getting the most bang for the buck": Identify features that are as useful as possbile, but also as easy/cheap/fast to implement as possible.

Domain experts know what is useful, SW devs know what's easy to implement. You need both pieces of information to decide which features are worth considering.

Title: How early is too early to be involved in new feature development?

Body:
I develop an internal business application that our engineers use to test and debug the company's product. The engineering manager has been pushing to get the software developers involved when the engineers are in their design phase. He says that he wants to give us an idea of what's coming down the pipe, and give us the opportunity to provide feedback on their designs (we rarely have feedback).

The engineering manager wants the developers and engineers to implement new features simultaneously, so that by the time the engineers have implemented their end, they can use the software to test them. The feature designs tend to be volatile until they are fully implemented by the engineers, making it difficult to draw up requirements. He thinks the engineers and developers can do all of our debugging side-by-side, at integration time.

It all seems inefficient and backwards to me.


答:
The answer below is wrong, but I'll keep it for others to learn from it (see below)

In ExampleA, you can use the same Config instance across multiple classes. However, if there should be only one Config instance within the entire application, consider applying the Singleton pattern on Config to avoid having multiple instances of Config. And if Config is a Singleton, you could do the following instead:

```<code>class ExampleA
{
  private $config;
  public function __construct()
  {
     $this->config = Config->getInstance();
  }
}
$exampleA = new ExampleA();
</code>```

In ExampleB, on the other hand, you'll always get a separate instance of Config for each instance of ExampleB.

Which version you should apply really depends on how the application will handle instances of Config:

if each instance of ExampleX should have a separate instance of Config, go with ExampleB;

if each instance of ExampleX will share one (and only one) instance of Config, use ExampleA with Config Singleton;

if instances of ExampleX may use different instances of Config, stick with ExampleA.

Why converting Config into a Singleton is wrong:

I must admit that I only learned about the Singleton pattern yesterday (reading the Head First book of design patterns). Naively I went about and applied it for this example, but as many has pointed out, one way are another (some have been more cryptic and only said "You're doing it wrong!"), this is not a good idea. So, to prevent others from making the same mistake that I just did, here follows a summary of why the Singleton pattern can be harmful (based on the comments and what I found out googling it):

If ExampleA retrieves its own reference to the Config instance, the classes will be tightly coupled. There will be no way of having an instance of ExampleA to use a different version of Config (say some subclass). This is horrible if you want to test ExampleA using a mock-up instance of Config as there is no way to provide it to ExampleA.

The premise of there will be one, and only one, instance of Config maybe holds now, but you cannot always be sure that the same will hold in the future. If at some later point it turns out that multiple instances of Config will be desirable, there is no way of achieving this without rewriting the code.

Even though the one-and-only-one instance of Config is maybe true for all eternity, it could happen that you want to be able to use some subclass of Config (while still having only one instance). But, since the code directly gets the instance via getInstance() of Config, which is a static method, there is no way to get the subclass. Again, code must be rewritten.

The fact that ExampleA uses Config will be hidden, at least when just viewing the API of ExampleA. This may or may not be a bad thing, but personally I feel that this feels like a disadvantage; for instance, when maintaining, there is no simple way of finding out which classes will be affected by changes to Config without looking into the implementation of every other class.

Even if the fact that ExampleA uses a Singleton Config is not a problem in itself, it may still become a problem from a testing point of view. Singleton objects will carry state which will persist until the termination of the application. This can be a problem when running unit tests as you want one test to be isolated from another (i.e. that having executed one test should not affect the outcome of another). To fix this, the Singleton object must be destroyed between each test run (potentially having to restart the whole application), which may be time-consuming (not to mention tedious and annoying).

Having said this, I'm glad that I made this mistake here and not in the implementation of a real application. In fact, I was actually considering rewriting my latest code to use the Singleton pattern for some of the classes. Although I could easily revert the changes (everything is stored in an SVN, of course), I would still have wasted time doing it.

Title: Should I pass an object into a constructor, or instantiate in class?

Body:
Consider these two examples:

Passing an object to a constructor

```<code>class ExampleA
{
  private $config;
  public function __construct($config)
  {
     $this->config = $config;
  }
}
$config = new Config;
$exampleA = new ExampleA($config);
</code>```

Instantiating a class

```<code>class ExampleB
{
  private $config;
  public function __construct()
  {
     $this->config = new Config;
  }
}
$exampleA = new ExampleA();
</code>```

Which is the correct way to handle adding an object as a property? When should I use one over the other? Does unit testing affect what I should use?

Body:
The answer below is wrong, but I'll keep it for others to learn from it (see below)

In ExampleA, you can use the same Config instance across multiple classes. However, if there should be only one Config instance within the entire application, consider applying the Singleton pattern on Config to avoid having multiple instances of Config. And if Config is a Singleton, you could do the following instead:

class ExampleA
{
  private $config;
  public function __construct()
  {
     $this->config = Config->getInstance();
  }
}
$exampleA = new ExampleA();

In ExampleB, on the other hand, you'll always get a separate instance of Config for each instance of ExampleB.

Which version you should apply really depends on how the application will handle instances of Config:

if each instance of ExampleX should have a separate instance of Config, go with ExampleB;

if each instance of ExampleX will share one (and only one) instance of Config, use ExampleA with Config Singleton;

if instances of ExampleX may use different instances of Config, stick with ExampleA.

Why converting Config into a Singleton is wrong:

I must admit that I only learned about the Singleton pattern yesterday (reading the Head First book of design patterns). Naively I went about and applied it for this example, but as many has pointed out, one way are another (some have been more cryptic and only said "You're doing it wrong!"), this is not a good idea. So, to prevent others from making the same mistake that I just did, here follows a summary of why the Singleton pattern can be harmful (based on the comments and what I found out googling it):

If ExampleA retrieves its own reference to the Config instance, the classes will be tightly coupled. There will be no way of having an instance of ExampleA to use a different version of Config (say some subclass). This is horrible if you want to test ExampleA using a mock-up instance of Config as there is no way to provide it to ExampleA.

The premise of there will be one, and only one, instance of Config maybe holds now, but you cannot always be sure that the same will hold in the future. If at some later point it turns out that multiple instances of Config will be desirable, there is no way of achieving this without rewriting the code.

Even though the one-and-only-one instance of Config is maybe true for all eternity, it could happen that you want to be able to use some subclass of Config (while still having only one instance). But, since the code directly gets the instance via getInstance() of Config, which is a static method, there is no way to get the subclass. Again, code must be rewritten.

The fact that ExampleA uses Config will be hidden, at least when just viewing the API of ExampleA. This may or may not be a bad thing, but personally I feel that this feels like a disadvantage; for instance, when maintaining, there is no simple way of finding out which classes will be affected by changes to Config without looking into the implementation of every other class.

Even if the fact that ExampleA uses a Singleton Config is not a problem in itself, it may still become a problem from a testing point of view. Singleton objects will carry state which will persist until the termination of the application. This can be a problem when running unit tests as you want one test to be isolated from another (i.e. that having executed one test should not affect the outcome of another). To fix this, the Singleton object must be destroyed between each test run (potentially having to restart the whole application), which may be time-consuming (not to mention tedious and annoying).

Having said this, I'm glad that I made this mistake here and not in the implementation of a real application. In fact, I was actually considering rewriting my latest code to use the Singleton pattern for some of the classes. Although I could easily revert the changes (everything is stored in an SVN, of course), I would still have wasted time doing it.


答:
Do not forget about testability!

Usually if the behavior of Example class depends on the config you want to be able to test it without saving/modifying the internal state of the class instance (i.e. you would want to have simple tests for happy path and for wrong config without modifying the property/memeber of Example class).

Therefore I would go with first option of ExampleA


答:
typedef fits the C++ philosophy: all possible checks/asserts in compilation time. #define is just a preprocessor trick which hide a lot of semantic to the compiler. You should not worry about compilation performance more than code correctness.

When you create a new type you are defining a new "thing" that your program's domain manipulates. So you can use this "thing" to compose functions and classes, and you can use the compiler for your benefit to do static checks. Anyway, as C++ is compatible with C, there are a lot of implicit conversion between int and int-based types which do not generate warnings. So you don't get the full power of static checks in this case. However, you could replace your typedef with an enum to find implicit conversions. E.g.: If you've typedef int Age;, then you can replace with enum Age { }; and you will get all kind of errors by implicit conversions between Age and int.

Another thing: the typedef can be inside a namespace.

Title: typedefs and #defines

Body:
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.

Consider the below 2 situations to use int data type with another name:

```<code>typedef int MYINTEGER
</code>```

and

```<code>#define MYINTEGER int
</code>```

Like above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.

Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).


问:
What is the best way to access multiple child properties?
I have a situation where I have to access several "sub-properties" of an object and find it quite appalling to write such code.

I was wondering how best to deal with this situation:

```<code>void Main()
{
    MyAClass aClass = new MyAClass();
    aClass.BClass.CClass.DoSomething();
}
</code>```

In addition to it being an eyesore, there are no null checks, and if one were to do them, the code would look even more cluttered.

At the moment I create shortcuts, but they are a bit of a code smell too:

```<code>public class MyAClass
{
    public MyBClass BClass { get; set; }

    public void DoSomething()
    {
        if (BClass == null || BClass.CClass == null)
            throw new Exception();

        BClass.CClass.DoSomething();
    }
}
</code>```

What's the best way to access multiple properties like this?

答:
This is really a design problem.  The caller is required to have knowledge (i.e., "a dependency") on the internals of MyAClass - and in this case, not only on the internals of MyAClass, but also internals of the instance MyBClass that MyAClass holds, the instance of MyCClass that BClass holds, etc.  There are several problems with this design - notably, it will be fragile and difficult to change (i.e., modifications to MyCClass could impact not only this caller, but also MyAClass, MyBClass, etc.), and you'll have an ownership/order-of-instantiation problem (i.e., as you mention, "no null checks") - this API requires that each of the classes has a non-null instance of each object already initialized, or worse yet, the property "getter" will do a null check and then instantiate one before returning the new object.  This is really bad because what looks like a simple property "get" call, could result in some huge memory allocation or operation.

Long story short, if the caller really needs to have knowledge of these other classes, perhaps you can redesign the API, so that the caller allocates instances of each of the objects (either by an explicit "new" or via a factory), and passes them to MyAClass as constructor arguments, effectively making the caller the "owner".

Big-picture wise, I'd recommend reading a great book I've recently come across - "API Design for C++" by Martin Reddy - it's focused on C++, but the design issues are largely the same.  You could also check out the "Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner and "More Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner for some useful tidbits on .NET API design.


问:
What is the difference between a function and a lambda?
I'm a little bit confused about 'function' and 'lambda'.  I've seen some examples showing that the scheme keyword lambda works very similarly to the JavaScript keyword function, but I really don't know how they are related.

I'm told that 'function' and 'method' can be used interchangeably when speaking about objects in .net.  I'm wondering if 'lambda' and 'function' similarly mean the same thing.  I wonder if 'lambda' has some esoteric meaning, seeing that the Greek letter lambda (λ) appears in so many avatars on this site.  To make things even more confusing, in .net, the functional parts of C# refer to function expressions passed to another function as 'lambda expressions', so the word really seems to be all over the place.

I'm also vaguely familiar with the term 'lambda calculus'.

What is the difference between a function and a lambda?

答:
Answered Here:
https://stackoverflow.com/questions/16501/what-is-a-lambda-function

Basically Lambda is an anonymous function.


答: A lambda is simply an anonymous function - a function with no name.</p>

Body:
I'm a little bit confused about 'function' and 'lambda'.  I've seen some examples showing that the scheme keyword lambda works very similarly to the JavaScript keyword function, but I really don't know how they are related.

I'm told that 'function' and 'method' can be used interchangeably when speaking about objects in .net.  I'm wondering if 'lambda' and 'function' similarly mean the same thing.  I wonder if 'lambda' has some esoteric meaning, seeing that the Greek letter lambda (λ) appears in so many avatars on this site.  To make things even more confusing, in .net, the functional parts of C# refer to function expressions passed to another function as 'lambda expressions', so the word really seems to be all over the place.

I'm also vaguely familiar with the term 'lambda calculus'.

What is the difference between a function and a lambda?


答:
The word "lambda" or "lambda expressions" most often refers to anonymous functions. So in that sense a lambda is a kind of function, but not every function is a lambda (i.e. named functions aren't usually referred to as lambdas). Depending on the language, anonymous functions are often implemented differently than named functions (particularly in languages where anonymous functions are closures and named functions are not), so referring to them with different terms can make sense.

The difference between scheme's lambda keyword and Javascript's function keyword is that the latter can be used to create both anonymous functions and named functions while the former only creates anonymous functions (and you'd use define to create named functions).

The lambda calculus is a minimal programming language/mathematical model of computation, which uses functions as its only "data structure". In the lamdba calculus the lambda-symbol is used to create (anonymous) functions. This is where the usage of the term "lambda" in other languages comes from.

Title: What is the difference between a function and a lambda?


答:
You are right, it's a code smell and a potential problem (if any child in chain is null).

To avoid this you should follow the rule of code access level - I don't quite remember the statement, but the thing is:

Your method must do only one thing (single responsibility) and do not operate on the different levels of the objects.

In your example, since you have BClass instance as a member of MyAClass, DoSomething() method should only access properties/methods of that member and never properties of properties.

Potential resolution:

Introduce method in MyBClass

```<code>public class MyBClass
{
    public MyCClass BClass { get; set; }

    public void DoSomething()
    {
        CClass.DoSomething();
    }
}
</code>```

and call it in MyAClass.DOSomething()

Consider refactoring the code and replacing MyBClass member with MyCClass.

Title: What is the best way to access multiple child properties?

Body:
I have a situation where I have to access several "sub-properties" of an object and find it quite appalling to write such code.

I was wondering how best to deal with this situation:

```<code>void Main()
{
    MyAClass aClass = new MyAClass();
    aClass.BClass.CClass.DoSomething();
}
</code>```

In addition to it being an eyesore, there are no null checks, and if one were to do them, the code would look even more cluttered.

At the moment I create shortcuts, but they are a bit of a code smell too:

```<code>public class MyAClass
{
    public MyBClass BClass { get; set; }

    public void DoSomething()
    {
        if (BClass == null || BClass.CClass == null)
            throw new Exception();

        BClass.CClass.DoSomething();
    }
}
</code>```

What's the best way to access multiple properties like this?

Body:
You are right, it's a code smell and a potential problem (if any child in chain is null).

To avoid this you should follow the rule of code access level - I don't quite remember the statement, but the thing is:

Your method must do only one thing (single responsibility) and do not operate on the different levels of the objects.

In your example, since you have BClass instance as a member of MyAClass, DoSomething() method should only access properties/methods of that member and never properties of properties.

Potential resolution:

Introduce method in MyBClass

public class MyBClass
{
    public MyCClass BClass { get; set; }

    public void DoSomething()
    {
        CClass.DoSomething();
    }
}

and call it in MyAClass.DOSomething()

Consider refactoring the code and replacing MyBClass member with MyCClass.


答:
Look at it as a prototyping problem.  A prototype is a means of requirements gathering, where the creation of something physical that reflects the current thinking so far can help solidify whether it is what they want, or if there are really more or different requirements.

If the engineers are putting together some basic ideas with the developers on hand, the developers should be able to not only say whether it is feasible, but they should also be able to throw together a prototype that could be the basis for the real application.  Taken to its logical extreme, this becomes an incremental, iterative method of design and development, in the vein of the unified process and/or agile.

I'd also point out that the developers SHOULD be giving feedback.  How is it that yours don't?


答:
There is nothing wrong with getting developers involved with the requirements phase if your company can afford it. This doesn't mean that they will start other phases of the development cycle any sooner.

In my experience, it is often invaluable to have a sharp developer involved early in the requirements gathering process as they can help the team avoid any issues that arise based on unsound development assumptions by management/business. However, this could also be a huge waste of the developers time if the requirements phase turns into a weak brainstorming session.

There really is no hard and fast rule to when developers should get involved. I have been on projects where I was brought in too late, only to be brought in too early on the next because they recognized this and tried not to make the same mistake twice. If your company doesn't have strong leadership who can weigh when to bring developers in, there may be many frustrated developers sitting in on "it would be cool if we could..." meetings.

A good project manager should know the right time to get developers involved. This is difficult because the project manager would have to understand both the progress of the requirements, and their own limitations when it comes to their technical understanding. A great project manager will know which developers should be involved at what phase (as some developers are better at the requirements phase than others).

I have yet to see a project that has made it completely through the requirements phase that couldn't have used some input by a developer. If that is happening anywhere, I would like my company to hire those project managers/analysts.


答:
The first approach violates the Law of Demeter and Tell, Don't Ask.

The point of OOP is not to be pretty, but to have a strong and simple way of achieving modularity. Modules are the means to apply divide and conquer to software development itself, where the conquest is achieved through implementation and the division is achieved through interfaces. Interfaces are all that really matters.

Nobody really cares how you implement something, as long as it is correct and reasonably fast. What's far more important is its handiness. Expecting user's of your code to go exploring your object graphs is not handy for them. Whatever components you wire together to achieve your goal is your business.

A user of your code just wants to DoSomething and your class allows them to do that. That is your contract. And the establishment (and upholding) of such a contract increases robustness, because you are free to change the way you accomplish that something without breaking any outside code.


问:
How is Python used in the real world?
I'm looking to get a job as a Python programmer. I know the basics of the language and have created a few games with it using pygame. I've also started to experiment with Django.

However, looking at the job market, it doesn't seem very many Python jobs are web-related. On the desktop side of things, it doesn't seem like very many companies use the popular GUI libraries like pyQt or wxPython.

How are companies actually using Python? What areas should one focus on to land a job as a Python programmer?

答: Python can also be used for report generation, deployment scripting, and numerical processing in scientific and graphical applications. I've most often used it in generating financial reports out of SQL databases. </p>

Title: How is Python used in the real world?


问:
When am I ready to start using Jquery for Javascript?
I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>

答:
I am not certain I would insist on one before the other, but using jquery without a decent understanding of the underlying features of javascript sometimes leads to some odd complexity when a newer dev starts writing everything from a jquery point of view first.

Use both, but be careful not to create complexity where it is not required.  Some of those jquery functions can be quite expensive/complicated.  On several projects I have had to replace jquery with plain javascript because they didn't perform as well as they should have at scale or on slower clients.

IMHO the jquery is probably best mixed with more plain javascript than I see in many cases.

OwnerDisplayName: Cornucopia

LastEditorDisplayName: Cornucopia


问:
Is there a design pattern that would apply to discount models?
Are there any known design patterns for implementing discount models?

By discount models, I mean the following:

If a customer buys Product X, Product Y and Product Z he gets a discount of 10% or $100.

If a customer buys 100 units of Product X, he gets a discount of 15% or $500

If a customer has brought in the last year more than $100K, he gets a flat 20% discount

If a customer has purchased 2 units of Product X, he gets 1 unit of Product X (or Product Y) free.

...

Is there a generic pattern that can be applied to handle all of the above scenarios? I am thinking of a few models, but unable to come across a generic one.

答:
Is there is any point is asking if there is a useful pattern for this? What type of pattern is required - structural or behavioral?

Ideally, if i were to write a software for this, all it will take is an algorithm. A simple function that calculates total discount as follows:

```<code>cart.calculateDiscount(productVector);
</code>```

You don't quite need anything more than this!

To clarify: I understand that there will be many rules - most basic of such representation should be in the form of a rulebase (set of data attributes and resultant discount against it) and the function such as above would iterate it to compute it. If rules gets added or removed you shouldn't end up changing the code- just change the rule base.

Pattern will be required only if we need different objects needs to access API's of each other or communicate to put a task in place.

PS: Think about it - when firewall processes packets and passes or rejects packets (or modifies it) - what design pattern does it use? The answer is NONE of the above described!

Body:
Is there is any point is asking if there is a useful pattern for this? What type of pattern is required - structural or behavioral?

Ideally, if i were to write a software for this, all it will take is an algorithm. A simple function that calculates total discount as follows:

cart.calculateDiscount(productVector);

You don't quite need anything more than this!

To clarify: I understand that there will be many rules - most basic of such representation should be in the form of a rulebase (set of data attributes and resultant discount against it) and the function such as above would iterate it to compute it. If rules gets added or removed you shouldn't end up changing the code- just change the rule base.

Pattern will be required only if we need different objects needs to access API's of each other or communicate to put a task in place.

PS: Think about it - when firewall processes packets and passes or rejects packets (or modifies it) - what design pattern does it use? The answer is NONE of the above described!


问:
Are there good techniques or tests for naming types?
An awkward, open question, but it's a problem I'm always bumping against:

Software that's easy to maintain and work with is software designed well. Trying to make a design intuitive means naming your components in such a way that the next developer should be able to infer the function of the component. This is why we don't name our classes "Type1", "Type2", etc.

When you're modelling a real-world concept (e.g. customer) this is generally as simple as naming your type after the real-world concept being modelled. But when you're building abstract things, which are more system-oriented, it's very easy to run out of names which are both easy to read and simple to digest.

It gets worse (for me) when trying to name families of types, with a base-type or interface which describes what the components have to do, but not how they work. This naturally leads to each derived type trying to describe the flavour of the implementation (e.g. IDataConnection and SqlConnection in the .NET Framework), but how do you express something complicated like "works by reflection and looking for a specific set of attributes"?

Then, when you've finally picked a name for the type you think describes what it's trying to do, your colleague asks "WTF does this DomainSecurityMetadataProvider actually do?"

Are there any good techniques for choosing a well-meaning name for a component, or how to build a family of components without getting muddled names?

Are there any simple tests that I can apply to a name to get a better feel for whether the name is "good", and should be more intuitive to others?

答:
Use metaphors to describe parts of the system. Not only it will make you discover new analogies, it will help naming easier.

(I am aware this is not a strong example but anyway) For example you can call a variable or a type  as mailbox, which serves as a queue for the received messages for a class.


答:
Using defines instead of typedefs is troubling under another important aspect, and namely the concept of type traits. Consider different classes (think of standard containers) all of which define their specific typedefs. You can write generic code by referring to the typedefs. Examples of this include the general container requirements (c++ standard 23.2.1 [container.requirements.general]) like

```<code>X::value_type
X::reference
X::difference_type
X::size_type
</code>```

All of this is not expressible in a generic way with a macro because it is not scoped.

Title: typedefs and #defines

Body:
Using defines instead of typedefs is troubling under another important aspect, and namely the concept of type traits. Consider different classes (think of standard containers) all of which define their specific typedefs. You can write generic code by referring to the typedefs. Examples of this include the general container requirements (c++ standard 23.2.1 [container.requirements.general]) like

X::value_type
X::reference
X::difference_type
X::size_type

All of this is not expressible in a generic way with a macro because it is not scoped.


问:
How do I choose what code to review?
I am part of a team of seven developers in a small software company and I am trying to introduce regular group code and design reviews. We have carried out some reviews in the past, but it has been sporadic. I would like to make it a more regular thing.

I have read Code Complete and other similar resources and they talk about the mechanics of how to carry out code reviews but I have been unable to find any best practices on how to choose what to review. We have a code base that is more than eight years old and covering a variety of languages, so there is plenty that could be looked at.

Here are some of the factors that I can think of that might affect the choice:

Language: C, Java, SQL, PL/SQL

Code age: New code vs old code

Code usage: Frequently used code vs (effectively) dead/little used code

Code importance: Critical code vs non-critical code

Developer: Junior developer code vs Senior developer code

I understand that this isn't a question with an absolute definitive answer, but any guidance would be useful.

Some peripherally related questions:

Code review approaches (Mentions of reviewing critical sections and new developer code)

Should we attempt to review all our code?

答:
In general, you must review everything. If a fresh application has 2 000 LOC, all 2 000 LOC must be reviewed.

That's why there is no best practice on how to choose what to review.

If you approach an existent large codebase, never reviewed before, then it's the same thing when you must rewrite an existent large codebase, and to choose where to start. It strongly depends:

on the codebase (a single monolithic code would be more difficult to rewrite/review than a set of separate components, etc.),

your context (can you stop everything you work on and spend three months (three years?) working only on rewrite/review, or you must do it by small lapses, only when you have free time)?

the type of review you do (do you have a checklist of things to review? Depending on the items of the checklist, you may want to review some parts first).

If I were you, I would:

follow the 80%-20% principle, mentioned in the first comment of the second question you linked to.

take in account that 100%, being an ideal, isn't maybe worth it. It's like 100% code coverage for unit tests, except that such code coverage is mostly impossible or extremely expensive.

start with the parts of the code you use the most and which are the most important. If the codebase has a library which authenticates and registers new users on your corporate website, review it first, because you want certainly find security holes before hackers do.

use existent metrics to determine what is more important to review. If a part of the codebase has no unit tests at all, while another, equally important part, has 85% code coverage, start by reviewing the first part. If a part of the codebase was written by a developer who was known to be inexperienced and to introduce more bugs than any of his colleagues, start by reviewing his code first.

Title: How do I choose what code to review?


问:
What is a realistic way to handle customer-specific software patches?
I'm trying to gather effective ways that others have solved the following problem.  At work we've been forced to release a software patch (to be installed on end-user systems) that we only want visible to a specific customer.  The custom code is in its own source-control branch.  The problem is we have two parallel code lines (and build scripts) to keep in sync, and every time we patch the original code we have to patch and test the customer-specific code.

I'm curious, how do other organizations handle this scenario?  We're open to business solutions and not just technical (source-control related) ones.  For example, we've talked about telling the customer they can't receive updates on that branch.

Our branching strategy is like this (based on the Visual Studio TFS Branching Guide, although we're using Subversion for it)

答: It seems to me the key is "visible"--what about not having a separate code branch at all, but rather a configuration option that changes the behavior?</p>


问:
How independent is Clojure from Java?
I am quite new to the Clojure world. I appreciate the fact that one has easy access to all Java libraries via Clojure interop features, but I was wondering how much Clojure stands on its own legs.

Of course there are some platforms, like Android, where interoperability with Java will always be required, because the core libraries are written or exposed in Java. Moreover, since Clojure strings are Java strings, I expect string manipulation libraries to be a wrapper on the Java String methods.

But for other tasks I see no reason why native Clojure libraries couldn't be developed. Think of Http, date manipulation, XML parsing, templating, JSON serialization and deserialization, OAuth, math libraries and so on.

So my question is:

How far has Clojure come to become independent of the Java ecosystem? Does it have its own idiomatic libraries for most of these and other tasks?

答:
I think it's fair to say that Clojure is designed as a hosted language and it now has three implementations:

Clojure on JVM

ClojureCLR on .NET

ClojureScript on JavaScript

Because it is designed as a hosted language, the idiom is to leverage the underlying platform's libraries where it makes sense but also provide a set of "core" libraries that are portable (from a usage p.o.v., not necessarily at the code level). I expect over time we'll see a lot more Clojure libraries running on all three platforms, where it makes sense.

I maintain clojure.java.jdbc and clj-time (a wrapper around JodaTime) so it doesn't make sense to use those on the *CLR or *Script versions but API-compatible libraries in different namespaces might be a possibility.

Many of the "pure" Clojure libraries should be straightforward to use on the *CLR or *Script versions already.

To the OP's question: "Clojure-the-language" is pretty portable but "Clojure-the-implementation" is deliberately bound to the Java ecosystem, as is ClojureCLR to .NET and ClojureScript to JavaScript.

Title: How independent is Clojure from Java?


答:
Start by reviewing all changes you make to the code; that will stop the problem getting worse.  Then start reviewing code based on frequency of changes; these will be the 'problem' areas.

You'll want to figure out some way to  track that you have reviewed a section of code so you can analyze the review coverage of your code relative to other concerns.

If you can determine what code is not covered by your tests, that becomes higher priority for review.

Title: How do I choose what code to review?

Body:
I am part of a team of seven developers in a small software company and I am trying to introduce regular group code and design reviews. We have carried out some reviews in the past, but it has been sporadic. I would like to make it a more regular thing.

I have read Code Complete and other similar resources and they talk about the mechanics of how to carry out code reviews but I have been unable to find any best practices on how to choose what to review. We have a code base that is more than eight years old and covering a variety of languages, so there is plenty that could be looked at.

Here are some of the factors that I can think of that might affect the choice:

Language: C, Java, SQL, PL/SQL

Code age: New code vs old code

Code usage: Frequently used code vs (effectively) dead/little used code

Code importance: Critical code vs non-critical code

Developer: Junior developer code vs Senior developer code

I understand that this isn't a question with an absolute definitive answer, but any guidance would be useful.

Some peripherally related questions:

Code review approaches (Mentions of reviewing critical sections and new developer code)

Should we attempt to review all our code?


问:
What legal considerations do I need to have when programming?
Recently I worked with a group to create a logging system for tutoring labs to track Tutor hours, and usage of the labs. We had to change the design a fair amount to be in compliance with FERPA. </p>

<p>My question stems from the curiosity that in my course of study there has never been a real mention of how people in this field have to deal with complying with the law in their work. So I would like to know how much programmers have to consider the law in the work they do. </p>

答: Though I've never had to deal with it, I have heard that Sarbanes-Oxley compliance has forced a fair bit onto many projects.</p>


答:
Start by reviewing all new code, and modifications to existing code.

When reviewing modifications to existing code, the developer should follow the boyscout rule.  Leave the code better than he found it.

That doesn't mean that you have to fix the entire file to be perfect.  But it shouldn't add to the mess, it should make it a little better.  Perhaps by moving the modifications into new classes that are properly structured, and leaving the rest of the original code file as is (after all, its' working).

Once you start improving the code by reviewing all new code and modifications, as developers, you should know what areas of the application require the most change.  Then, review those, discuss how they can be improved, little by little.

Reviewing code written 10 years ago, for the sake of reviewing it, is pointless, the developer should have improved over those 10 years.  So, there's no point reviewing it just to learn what you all know.

The purpose of code reviews is to improve and correct mistakes you are currently making and to share that knowledge amongst the team.

Title: How do I choose what code to review?


答:
Logically, a discount model can be anything, so you can't assume you can program all cases in advance.  Nor can anyone answering your question be completely sure what you actually need.  However, assuming you get the usual kinds of discounts found in the real world...

A big question is whether the discounts will be programmed, or if you want users to enter them.  As mentioned above, you can't never have them be programmed, but usually the goal is to try to make it more data entry like for common cases, rather than programming them all.  This applies to some extent even if programmers are used to create all the discounts.

Martin Fowler mentions "Individual Instance Method" in "Analysis patterns: reusable object models" as part of how to implement "Posting Rules" for accounting systems, but the rules seem fairly similar to yours.  I'd give more detail but it's a copyrighted work and

For a user interface, you either need to come up with use-cases that are fairly simple, or else build an interpreter and query builder.  Possibly both, one for simple cases and one more advanced.  If you do write an interpreter, this is likely a fairly good case for using the Interpreter pattern, since it's relatively simple to code compared to a parser generator, and the slower parse time probably won't really matter.  (If you like using parser generators don't let me stop you).

Don't try to do everything with an interpreter though - at some point you are just programming in your own crummy language, so you might as well use a real one.  If your interpreted language supports functions (it probably should support calling them - defining them is dubious) those can be coded in a real language.  Don't go further down this road than you have to.

No matter what you do, eventually someone will want the discount to be based on whether they purchased within 30 business days of a promotion - where business days count only if there was no holiday in the region defined by either the store's postal code or the client's postal code.  So don't try to design the perfect system in advance - assume you will sometimes need to write code for new kinds of discounts and design accordingly.

Title: Is there a design pattern that would apply to discount models?

Body:
Are there any known design patterns for implementing discount models?

By discount models, I mean the following:

If a customer buys Product X, Product Y and Product Z he gets a discount of 10% or $100.

If a customer buys 100 units of Product X, he gets a discount of 15% or $500

If a customer has brought in the last year more than $100K, he gets a flat 20% discount

If a customer has purchased 2 units of Product X, he gets 1 unit of Product X (or Product Y) free.

...

Is there a generic pattern that can be applied to handle all of the above scenarios? I am thinking of a few models, but unable to come across a generic one.


答:
Do you see this as a short term or long term thing? The fact is the business has already decided to accommodate this customer so short term it already IS a business decision to be primarily solved by business practices (accepting the extra cost/charging the customer for the cost).

If long term then you will probably see savings if you re-factor the software to easily accommodate that customers needs through configuration (or setup etc).

If it is relatively short term meaning you will soon merge those changes back into the main/development branch and all users will also see the changes then it will probably be acceptable to work within the limitations of your current situation. Like I said the decision of what to do should have been made when the decision to accommodate the customer was made.

Long story short. Long term fix it technically, Short term deal with it.

Of course there is a point where it is a coin toss. If you are at that point then I would do whatever the developers prefer.

Title: What is a realistic way to handle customer-specific software patches?

Body:
I'm trying to gather effective ways that others have solved the following problem.  At work we've been forced to release a software patch (to be installed on end-user systems) that we only want visible to a specific customer.  The custom code is in its own source-control branch.  The problem is we have two parallel code lines (and build scripts) to keep in sync, and every time we patch the original code we have to patch and test the customer-specific code.

I'm curious, how do other organizations handle this scenario?  We're open to business solutions and not just technical (source-control related) ones.  For example, we've talked about telling the customer they can't receive updates on that branch.

Our branching strategy is like this (based on the Visual Studio TFS Branching Guide, although we're using Subversion for it)


答:
When you start giving out customer specific patches you have immediately created a new version of your product that must be maintained along side of it. That means changes have to be propagated between the two versions. Usually customer specific patches are customizations that should be owned by the customer, including the source code.

It seems unlikely that a patch to fix something would not make it into the mainline branch unless this is a less than optimal temporary fix for an immediate problem. If that is the case then the patch will only need to be maintained until the expected fix makes it into the mainline.


问:
Is 'process debt' a term people work with
As a result of a retrospective we were uncovering worse ways of developing
software. We had a idea we though was great and tried it. We stayed with it during the development of a major update which took 3 months. After a retrospective with the maintenance engineers it turn out our idea does not work for them (we had discussions with them before we tried the idea and the also thought it was a great idea). We came to the agreement we better get back to the old situation. The team for the update is dismantled and the maintenance engineers don't have time to do so (although their project manager has agreed to invest the time).

We're now in the situation the maintenance engineers pay the interest each time a minor release has to be made. This is very much like technical debt but has nothing to do with the product itself. Is this called process debt or is this put under the term technical debt? And what would be a good way of dealing with it? (Any other or concrete ideas to make it visible to product managers?)

PS The idea was migrating a 4 product VSS database to SVN. The database heavily leans on shared files and is a mess to untangle and pour in a usable SVN structure. It's very counter intuitive but is seems some things are better kept in VSS.

答: It sounds like you are describing muda, waste from Lean software engineering.  Obviously, you want to reduce waste as much as possible...


问:
Why does email sent from my site end up in SPAM folders?
I am developing a course registration website in Django. New users must confirm their email address by clicking on a link emailed to them.

Unfortunately, this message is consistently ending up in people's spam folders. What steps can I take to prevent this from happening? Should I include an unsubscribe paragraph? Should I send less mass mail from my site (I occasionally send out a message to 500 emails.)?

答:
Avoid any string that looks like spam.

Most Spam checking these days is Bayesian, which means that that your
  message is checked using a fuzzy algorithm that tries to guess if
  resembles known Spam or Ham (good) messages (mainly by checking the
  frequency of common spam words and phrases).

Send individual messages to each recipient instead of copies.

It is better to send an individual message to each recipient, rather
  than using multiple addresses in the BCC field because many spam
  filters (and many ISP's) automatically flag multiple recipients as
  spam.

If possible send via your ISP's mail server rather than using a local SMTP Server.

Messages sent from a mail server running on your computer may be
  flagged as spam because some mail servers will try to contact the
  source IP of the sending server (which will fail with a local IP
  address).

Try with smaller batches of e-mails.

It would appear that some of the big mail hosts such as Hotmail will
  recognize when an identical message is sent to a large number of
  subscribers at one time so you should stagger the delivery of your
  messages [...]  to send your messages in small batches.

Minimize your use of attachments.

Make sure the computer sending the email has a Reverse PTR record.

What's a reverse PTR record? It's something your ISP has to configure
  for you -- a way of verifying that the email you send from a
  particular IP address actually belongs to the domain it is purportedly
  from.

Configure DomainKeys Identified Mail in your DNS and code.

What's DomainKeys Identified Mail? With DKIM, you "sign" every email
  you send with your private key, a key only you could possibly know.
  And this can be verified by attempting to decrypt the email using the
  public key stored in your public DNS records.

Set up a SenderID record in your DNS.

To be honest, SenderID is a bit of a "nice to have" compared to the
  above two. But if you've gone this far, you might as well go the
  distance. SenderID, while a little antiquated and kind of..
  Microsoft/Hotmail centric.. doesn't take much additional effort.

SenderID isn't complicated. It's another TXT DNS record at the root
  of, say, example.com, which contains a specially formatted string
  documenting all the allowed IP addresses that mail can be expected to
  come from.

Sources and additional information:

XeQute

Spamassassin FAQ

Jeff Atwood's post on the same subject

Post on the same subject on ServerFault


答:
Neglecting the fact this is a design problem, as has been mentioned in the other answers, there is a way to somewhat improve that code in C# when you can't add the method yourself. This is especially useful when you have to traverse even longer hierarchies.

```<code>void Main()
{
    MyAClass myAClass = new MyAClass();
    MyCClass inner = myAClass
        .IfNotNull( a => a.BClass )
        .IfNotNull( b => b.CClass );
    if ( inner != null )
    {
        inner.DoSomething();
    }
}
</code>```

The code for the IfNotNull extension method is:

```<code>public static TInner IfNotNull<T, TInner>(
    this T source,
    Func<T, TInner> selector )
    where T : class
{
    return source != null ? selector( source ) : default( TInner );
}
</code>```

Of course in a scenario where you would throw an exception anyhow and it would be an exception to encounter an object which is null along the path, you could just catch the NullReferenceException and act upon that in any way you want.

Body:
Neglecting the fact this is a design problem, as has been mentioned in the other answers, there is a way to somewhat improve that code in C# when you can't add the method yourself. This is especially useful when you have to traverse even longer hierarchies.

void Main()
{
    MyAClass myAClass = new MyAClass();
    MyCClass inner = myAClass
        .IfNotNull( a => a.BClass )
        .IfNotNull( b => b.CClass );
    if ( inner != null )
    {
        inner.DoSomething();
    }
}

The code for the IfNotNull extension method is:

public static TInner IfNotNull<T, TInner>(
    this T source,
    Func<T, TInner> selector )
    where T : class
{
    return source != null ? selector( source ) : default( TInner );
}

Of course in a scenario where you would throw an exception anyhow and it would be an exception to encounter an object which is null along the path, you could just catch the NullReferenceException and act upon that in any way you want.


答:
Review all new changes that have been made before they make it to production. installation scripts, source code, database changes, everything! The whole point of code review is to stop bad code from making it into production. Be it a poor organizational scheme or simply an introduced bug because something was missed.

Refactoring the current code you are working on goes hand in hand with code review. For example, when I'm reviewing code, if there was duplicate code in a class that contained a bug fix, even if the developer didn't change that code in their fix, I would not pass it. I would have them go back and remove the duplicate code.

If you refactor relentlessly then code review becomes useful. Otherwise it is a waste of time.

If you incorporate the code review process as step in your development process the code base will get better over time. Better yet, you should not allow your developers to take on new feature work or bug fixes until the code review backlog is empty. This ensures that code review gets done.

If there are known areas that need to be refactored, but it will take a long time to do them (i.e. 1 week or more). Then create a work item for that refactoring by itself and add it as an item to be worked on.

Title: How do I choose what code to review?


问:
Finding an agile coach
I'm hoping that this is the right place to ask this question, but my company has recently started a process to look at how we build software, from the tools we use to the methodology. As you can imagine we have the kind of endless meetings where we sit around a table and split hairs.

In an effort to actually get something done I've suggested we hire in a professional to take a look at how we do what we do and maybe guide us into a more agile approach to delivering software.

My problem is that I'm not sure how to find a consultant we could bring in and get us started?

I was thinking of approaching someone like ThoughtWorks, but I think finding someone who isn't going to push an agenda or product on us would be better.

In the meantime I've picked up a few books and will do a bit of reading on the beach over the holiday vacation.

答:
I would look at hiring a professional. If you were able to get Thoughtworks I would jump at it. Yes they have their own products, but if you read one of their books the mention their product but don't push it. And those guys seem to be the best in the field.

But from anecdotal information in Wellington, New Zealand where I work. There are a lot of Agile consultants who can come in and recite the mantra of the project management side of Agile, get good wall boards and feature planning sessions running. But we are missing skilled people who can provide details on the technical side of agile.

Things like:

how to improve continuous integration to get more value,

how to enable continuous delivery, how do we work when we have to work with legacy code (or develop more),

how to re-tool to remove the barriers between testing and development.

And just from stories I've heard acceptance and implementation of Agile would be going better if both the project management and technical sides were covered off better.

Title: Finding an agile coach


问:
Architecting an organization's web strategy. What is the preferred method here?
I'm working on a solution for an organization that needs to last them long term (as subjective as that is).

They currently have a Joomla installation whereby the CMS talks directly to the database, from there I have started "bolting on" the additions that they need for their environment (mobile app, kiosk, and lobby display). I've also started writing a RESTful service to talk to Joomla (not the joomla database) and the apps.

Here's a diagram of how it's currently going.

note: they already have the "public & admin" as well as the central db, google cal, email, and vimeo

Since I'm just getting started with this, I'm thinking that I should probably push for an appropriate design from the ground up. I'm suggesting this so that they have a good foundation moving forward.

Here's my suggestion to them

proposed architecture http://www.gliffy.com/pubdoc/3221292/L.png

Being that they already have some pieces in place, is it worth pushing for a new architecture? Also, am I on the right track with regards to the new architecture?

Lastly, it's worth noting that they're not totally satisfied with Joomla and are looking for a possible rebuild for that portion of their project anyways.

答:
First of all, there isn't really much of a comparison. The current architecture obviously grew as bits where added, and your approach is a re-design, the obvious advantage being you know exactly what the layers are and how individual components interact. It's obviously the better approach, you are introducing a middle service layer that essentially makes the top layer "data storage" agnostic.

There isn't much to discuss really, what you are proposing is fairly close to a typical three-tier architecture. The only possible disadvantage is that there is no obvious fall back for the middle tier, the CRUD web service. If that fails for whatever reason, everything fails. Depending on the company and the availability needs for your services, that might or might not be important, but always worth considering.

Since this is a proposal, I feel obliged to warn you that it's a fairly radical change. If it was presented to me on one of the mature projects I'm working on, I'd need a fairly good estimate of the cost before discussing it. Typically radical architecture changes, especially from the ground up re-designs, happen gradually in quite a few iterations. Don't be discouraged if your team rejects the approach, but if that happens make sure you evaluate any feedback and come back with an adjusted and a bit less ambitious proposal.

ContentLicense: CC BY-SA 4.0


答:
Clojure is becoming more and more independent of Java libraries as its code base grows and naturally diversifies.  A major strength of Clojure is that it can call Java, so to see Clojure code in the future that doesn't use java would be unlikely.  That being said, I have done a good deal of development w/o calling Java libs(command line args, basic text minupulation, etc).
Here's a list of pure clojure libraries: http://www.clojure-toolbox.com/</p>

Title: How independent is Clojure from Java?

Body:
I am quite new to the Clojure world. I appreciate the fact that one has easy access to all Java libraries via Clojure interop features, but I was wondering how much Clojure stands on its own legs.

Of course there are some platforms, like Android, where interoperability with Java will always be required, because the core libraries are written or exposed in Java. Moreover, since Clojure strings are Java strings, I expect string manipulation libraries to be a wrapper on the Java String methods.

But for other tasks I see no reason why native Clojure libraries couldn't be developed. Think of Http, date manipulation, XML parsing, templating, JSON serialization and deserialization, OAuth, math libraries and so on.

So my question is:

How far has Clojure come to become independent of the Java ecosystem? Does it have its own idiomatic libraries for most of these and other tasks?


问:
What Are the Cons of Publishing Beta Software in Android Market?
I've spent some time developing a little Android app to scratch my own itch. I'm considering publishing the current version as a beta in Android Market. Pros for publishing it now would be the potential to get feedback. It would also be a way to gauge interest in the app which could effect whether to develop it further at all.  What would be the cons of publishing beta in Android Market?</p>

答:
The only cons that come to mind are potentially tarnishing perception of the application (or of yourself as the developer) if it's poorly received and/or buggy. Only a very late beta should really be published in Android Market, if at all. If you want to gauge interest or have users do actual beta testing, make the APK downloadable on your website or Github, etc.

This reduces your potential audience (to people who can enable the install of non-Market apps), but it's still a pretty large number of users who have this capability, and you might get better testers.

That being said, if you just want to get it out into the wild, are fairly happy with it, and aren't using a developer account you ever plan to sell software on, you don't have much to lose putting it up in Market.

There's also a discusson here about publishing beta apps from the android-developers Google group.


答:
Not an answer to the direct question, but one to solve the VSS problem:

I migrated a VSS DB to SVN a few years back, we had a fair few shared files. It was horrible. So I identified these files and moved every one of them to a 'common' directory (thankfully we didn't have files that were shared all over the place between arbitrary projects, well not many).

Once they were placed in a common folder away from the projects, they could be fetched and updated using SVN's externals feature, and the project workspaces could be updated to reference the shared files in the shared file folder. From that point on, the code became a lot nicer and there was a lot less breakage when 1 file was changed that affected an unrelated project.

Title: Is 'process debt' a term people work with

Body:
As a result of a retrospective we were uncovering worse ways of developing
software. We had a idea we though was great and tried it. We stayed with it during the development of a major update which took 3 months. After a retrospective with the maintenance engineers it turn out our idea does not work for them (we had discussions with them before we tried the idea and the also thought it was a great idea). We came to the agreement we better get back to the old situation. The team for the update is dismantled and the maintenance engineers don't have time to do so (although their project manager has agreed to invest the time).

We're now in the situation the maintenance engineers pay the interest each time a minor release has to be made. This is very much like technical debt but has nothing to do with the product itself. Is this called process debt or is this put under the term technical debt? And what would be a good way of dealing with it? (Any other or concrete ideas to make it visible to product managers?)

PS The idea was migrating a 4 product VSS database to SVN. The database heavily leans on shared files and is a mess to untangle and pour in a usable SVN structure. It's very counter intuitive but is seems some things are better kept in VSS.


问:
Is the MIT license suitable for an open source library that is only used in unit testing scenarios?
Some time ago I developed a small project for use in unit testing scenario's and published it on Codeplex. Back then I choose the GPL license but I didn't really understand it. Today I changed it to MIT, because it's a much simpler license that I can understand.

I like to be recognized as the copyright holder, but I want everybody to be able to use the library without worrying about license issues. I think MIT covers both, but not 100% sure. 'Virality' is not an issue for this project.

Would this license (MIT) in any way prevent a person to use my library for the unit testing of a closed-source commercial or private project? In this regard, is my recent change to MIT a change for the better?

答: The MIT license is essentially a "do whatever you want with this software, just don't blame me if something goes wrong" license. It's quite liberal. So if you don't care how your library is being used (or abused) and just want to be recognized as its author, then go with the MIT license.</p>


问:
How should repetitive calendar tasks be stored in the database?
This is for a small personal project for micro-management. Basically, I store tasks in a SQLite3 database that looks like this:

```<code>    id INTEGER PRIMARY KEY AUTOINCREMENT
    label TEXT
    deadline INTEGER
</code>```

So each task has a due date (deadline) that is stored as a Unix Time Stamp. So far so good, I can do entries such as "tomorrow: visit grandma" and a new row gets created with "visit grandma" as the label and tomorrow transformed as Unix time for deadline.

Now I would like to enter new type of tasks: routines - tasks repeated on a time pattern, like "everyday: clean kitchen". How can such tasks be stored or modeled?

For the moment, I am thinking that, in the case of a task that needs to be done everyday, to generate new rows in my table that would have the same label, and the deadline field incremented by one day. In this case, I need to fix a limit in the future. For example, if I create a routine for every day, it creates a new row for everyday of the remaining year.

Is there a simpler way to do this? Am I missing some obvious database design principles?

答:
By far the most frequent operation will be to list all events occurring in a time period.  So optimize your data so that question can be answered by a simple SQL query.  I would create two tables:

```<code>CREATE TABLE events(start TIMESTAMP, end TIMESTAMP, name TEXT, user_id LONG,
                    recurrence_id LONG, ...);
CREATE TABLE recurrences(id LONG, start TIMESTAMP, end TIMESTAMP, name TEXT,
                         frequency ...);
</code>```

Index the event table by start and end times.  Then all queries can be answered from the events table very quickly.  When a recurrence is edited, simply delete and recreate all the corresponding events.

This advice is shamelessly repeated from a book by Tom Kite.

Body:
By far the most frequent operation will be to list all events occurring in a time period.  So optimize your data so that question can be answered by a simple SQL query.  I would create two tables:

CREATE TABLE events(start TIMESTAMP, end TIMESTAMP, name TEXT, user_id LONG,
                    recurrence_id LONG, ...);
CREATE TABLE recurrences(id LONG, start TIMESTAMP, end TIMESTAMP, name TEXT,
                         frequency ...);

Index the event table by start and end times.  Then all queries can be answered from the events table very quickly.  When a recurrence is edited, simply delete and recreate all the corresponding events.

This advice is shamelessly repeated from a book by Tom Kite.


答:
In my project we do include code review as a must-have in most cases for any assignment/user story/bug being developed. We are using scrum/agile processes and ticket/story is not moved to built (that is a backlog for QA) until unit tests are written and code review is completed.

We do use Atlassian FishEye analysis with Crucible code review integrated with JIRA+SVN for this purpose.

When developer checks the code in for a specific story he creates a new code review in FishEye, where he selects the other members of the team to do the review.

Once code review is completed, (tool highlights the changes submitted and allows to leave the comments for the specific line of code) the developer corrects the mentioned issues/implements the suggested improvements and moves the ticket into Built column in JIRA - that means story is ready to be tested and that there are no more code changes expected for this specific work item.

This also ensures QA doesn't test anything that might be changed and potentially be broken while refactoring the code after code review.

To sum up, all code must be reviewed - this supports the high quality of code, which usually results in a better design, readability, maintainability and testability of the code and improves development performance in a long run.

Title: How do I choose what code to review?


答:
I would say if you are an experienced programmer with other languages (PHP, Java, whatever), then there's no reason not to just start with jquery right off the bat.  Its just that immensely useful.  Besides, jquery is a framework, so you'd still be using javascript - just instead of messing around with DOM, you're using jquery.

If you are new to programming alltogether... then I'd say do a couple projects w/ javascript to get a basic understanding of client-side scripting without jquery, so you can learn a bit about what it is doing for you.  And then when you feel like you have a handle on things, move on to jquery.

Title: When am I ready to start using Jquery for Javascript?

Body: I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>


答:
Probably need a IDiscount interface as all the different discounts are the same thing, and we will want to deal with them conceptually as generic discounts.

The "this customer's order" class probably needs a collection of Discounts. List? Hash? Linked List? Don't care, yet. Discounts apply to the purchase, not the customer!

Keep Discount instance building separate from Customer, Shopping Cart, History, etc. It will change a lot - as @jfrankcarr pointed out.

Probably a different class for each discount as the algorithm and parameters for each discount vary wildly and unpredictably.

I see a lot of event handling as discount calculating responds to shopping cart changes, and vice versa.

Design Pattern Application

I see a strategy pattern. IDiscount is the interface for implementing different discount algorithms.

I see a factory. Certainly not a full-blown abstract factory pattern, but a single class at this point in the analysis. Reasonably, there must be a single place where there is sufficient context to decide what discounts apply and to then create them. One class. If the rules for applying discounts later explodes due to a Marketing Department mushroom party, any additional Discount Construction logic must still coalesce in this base factory class, I think.

I can see Chain of Responsibility. This is not mutually exclusive to the factory idea. Instead of iterating a discount collection, each discount calls the next guy. The "customer's order" class does not hold a collection of discounts in this case.

The "hmmmm...." factor in Chain of Responsibility, I think, is that each Discount has a reference to the next. The implication is that order matters. Which is not the case. Also, the concept CoR embodies is that one object cannot handle the request so it is passed "up to the next higher authority." Our model is different. The only request is to calculate. Every discount does this. The output or effect may be null but every discount calculates. I instinctively lean toward a higher real-world fidelity.

Assumptions

Discounts are based on current shopping cart and/or purchase history

Zero or more discounts may apply. There are no mutually exclusive discounts

Proper calculation is not dependent on the order in which discounts are applied.

What changes, what stays the same?

Discounts are very different. Different number and kind of parameters to make up each rule.

Arguments for qualifying discounts change as the shopping cart changes.

The number of discounts available changes

The discounts this customer qualifies for changes as his shopping cart changes.

Shopping history does not change in the context of this purchase

Total cost changes dynamically as a function of purchase lines and discounts applied.

After initial application a discount's output may change, as purchase quantity changes for example.


答:
In C# Anonymous function is a general term that includes both lambda expressions and anonymous methods (anonymous methods are delegate instances with no actual method declaration).

Lambda expressions can be broken down to expression lambda and statement lambda

Expression lambda:

```<code>(int x, string y) => x == y.Length
</code>```

Statement lambda is similar to expression lambda except the statement(s) are enclosed in braces:

```<code>(int x, string y) => {
         if (x == y.Length) {
             Console.WriteLine(y);
         }
}
</code>```

When we talk about lambda expressions in JavaScript that basically just means using a function as an argument in a call to another function.

```<code>var calculate = function(x, y, operation){
    return operation(x, y);
}

// we're passing anonymous function as a third argument
calculate(10, 15, function(x, y) {
    return x + y;
}); // 25
</code>```

Body:
In C# Anonymous function is a general term that includes both lambda expressions and anonymous methods (anonymous methods are delegate instances with no actual method declaration).

Lambda expressions can be broken down to expression lambda and statement lambda

Expression lambda:

(int x, string y) => x == y.Length

Statement lambda is similar to expression lambda except the statement(s) are enclosed in braces:

(int x, string y) => {
         if (x == y.Length) {
             Console.WriteLine(y);
         }
}

When we talk about lambda expressions in JavaScript that basically just means using a function as an argument in a call to another function.

var calculate = function(x, y, operation){
    return operation(x, y);
}

// we're passing anonymous function as a third argument
calculate(10, 15, function(x, y) {
    return x + y;
}); // 25


问:
Is using PhoneGap for your first ever mobile app a good idea?
I am a beginner programmer. I've gotten an AS degree in CS which exposed me to the basics of c++, data structures, and algorithms and have light experience with html/css/javascript from just messing around building my own basic websites. I am no where near a proficient professional programmer as of yet.

My question is, would using PhoneGap to attempt to develop my first "app" for android/ios/whatever be a good idea or should I start out making native apps first?

With all the hype over html5/javascript at the moment, PhoneGap seems too good to be true for a beginner like me.

Thoughts? pros/cons?

答:
I think it depends on where your interests lie.  If your interests are games and other local applications, you might consider going native.

If, on the other hand, your interests are more in the vein of business applications, HTML5 is probably your future, since you have to write the app only once, and communication with a remote database is relatively straightforward.


答:
The team I am currently working with is building a PhoneGap solution using jQuery and targeting Windows Phone, Android and - as an afterthought - iOS.

We've found that while it abstracts away a lot of tedious stuff and makes UI creation much easier, it still has its issues when it comes to cross-device compatibility and its integration with other frameworks.

My recommendation would be to try PhoneGap and see what you think, but focus strongly on understanding the HTML and JavaScript that is being abstracted away by PhoneGap so that working through behavioural inconsistencies becomes a little easier.

Title: Is using PhoneGap for your first ever mobile app a good idea?

Body:
I am a beginner programmer. I've gotten an AS degree in CS which exposed me to the basics of c++, data structures, and algorithms and have light experience with html/css/javascript from just messing around building my own basic websites. I am no where near a proficient professional programmer as of yet.

My question is, would using PhoneGap to attempt to develop my first "app" for android/ios/whatever be a good idea or should I start out making native apps first?

With all the hype over html5/javascript at the moment, PhoneGap seems too good to be true for a beginner like me.

Thoughts? pros/cons?


问:
How can I develop a Package Manager for Embedded Systems?
I need to develop/use a package manager for an embedded Linux system with the following properties:

A master fully controls which packages need to be installed (the slave has no possibility to ask the master anything)

Download speed on the device is slow that not just everything from the master distribution can be download to the target

Upgrading/Downgrading of packages must be possible

It should be possible to replace the package manager on the system itself

Possibility to replace the operating system itself

It's easily to recover from failures (power loss, ...), especially relevant when considering the two points above

Locks on the slave which have to be deleted manually are by no means allowed

If a new (meta?) package replaces an old (meta) package and there are some unneeded packages left, they're removed, to save space on the device

Define some form of order or dependency to install packages

Perhaps some form of a recovery system is need (how to detect that it is needed, how to boot it, ...)

Some points are just repeating other points, and some points are not necessarily something the package manager itself has to do.

I started to copy ideas from dpkg (especially how it install files and renames them later to reduce the time frame where something bad can happen) and use the deb format for packages itself (not using all of the fields).

I'm not sure myself, if this questions belongs to Programmers, but instead asking for a solution or anything like that, I'm more interested if other programmers faced the same problem and if there are any notable resources how this kind of problem is solved. Personally it happened to me too many times that embedded devices could be almost destroyed by a software update without any possibility (without special hardware) for recovery.

Some links that may be relevant for others are the following ones:

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

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

I could as well provide a pseudo code alike description for what I intend to do.

答:
As a rule with embedded systems you need a boot loader to manage OS updates. Typically you have a primary boot loader that boot straps the minimum amount of hardware needed to install a secondary boot loader.

Usually the primary boot loader will be able to install a basic program from a physically connected store such as USB or serial, which is usually the secondary boot loader. The idea of the primary boot loader is to prevent "bricking" of the device under any kind of software failure - so the primary boot loader can never be field upgraded, if at all.

As you appear to want to perform complex "Over the Air" updates, the primary boot loader is not a suitable place for it, but you want to be able to recover from a failed operation OTA. This will require a secondary boot loader that can manage this complexity, and install OS and OS updates as needed.

If you can tolerate the risk of a device update failing, and having to resort to a primary boot recovery, then you will not need the secondary boot loader.

Think of a normal PC - Primary is the BIOS recovery/ rollback jumper, secondary is the BIOS (Which can boot from a USB/DVD/NETWORK etc, and is upgradeable) and then the OS. The OS can install it's own updates, but if one of those fails badly, the BIOS can do a PXE Network boot and reinstall the OS.

You can make the Secondary as complex as needed, provided you have the time, as it can be updated, but KISS is essential.

What you are asking for is not trivial to build from scratch, Find someone that's done it before.  I am not familiar enough with Embeded Linux systems to know what might be out there for you to build on. The best advise I can give is : It will fail, you need a recovery mechanism, once you have a recovery mechanistic, it does not matter if it fails because you can recover, so focus on recovery, not prevention of failure. The focus on how many simultaneous failures do you need to recover from, just 1, 2, more...... More than 1 is extremely hard, more than 3 not even NASA goes there.


问:
when to load partial views
When creating a website, when should you load partial view and when should you do a complete page refresh?

I was looking at github's site and noticed that pretty much the only place they do partial loading is in a project's folder area.  I could see a couple places where they could have but didn't(tab navigation: feed, your actions, ...). But, Google plus does partial loads for search, and clicking on any of the header navigation buttons (pictures, games, circles, ...).

Why would you not do partial loading if the main container stays the same and the content is the only thing that is changing?

答:
When it's better for the user, costs can be justified, and the additional time on the project can be justified. You have to look at how much time you have, how much the additional time will cost and weigh it against the benefit to the user experience and to the value that it provides to the company.

If cost/time has no meaning (and it always should) then wherever the experience can be improved it should be improved.

Specifically to your question...

Why would you not do partial loading if the main container stays the
  same and the content is the only thing that is changing?

When the additional time/costs don't make sense for the added improvement. There is going to be more code and more maintenance.

Title: when to load partial views