答:
If you subscribe to a policy of "Clean Code", then you probably need to ask yourself if it is good practice to add comments at all.  If the code can only be clarified with a comment, then sure, add one, otherwise you should be able to easily understand what your code does simply by reading it (provided you are using sensible names for your variables, methods, Etc.).

Regardless of your personal view about whether commenting is good practice or not, a comment should contain information that is of direct value to the code that the comment is referring to. In this case, the question is whether adding an issue number adds value to the code. The problem I see with adding the issue number is that you can have a section of code that might be modified heavily in order to satisfy several issues, and after a while, it could be impossible to correctly identify which changes related to a specific issue.  Subsequent issues for example may require code relating to prior issues to be heavily refactored. This is perhaps an extreme example, however it does show how the issue numbers in comments in code can turn out to be pretty useless.

If you could guarantee that the situation I have just described would never happen, I'd still argue that the issue number itself is still pretty useless without a description of what the issue is about, and yet, all of this information really belongs in your issue tracking system and should need to be duplicated.  A better place to note the issue number would be in your version control system as a commit comment.  The advantage is that you can compare versions and see the code changes relating to a specific issue, while the issue number itself provides you with the identifier needed if you want to review the reason for the change in the code.

With all of this in mind, I'd suggest that it is not really good practice as such adding issue numbers into comments within your code.


问:
Is it an absolute must that we ignore/delete all compiled files before committing?
I am working on a Drupal theme. I am going to be using "intermediary" languages to develop it, ie Stylus for styles, and CoffeeScript for some of the front-end scripts.

I am going to be using a git hosting service to be able to share the code among colleges. I am also going to be using it to update the code locally and then push onto hosting service, to be later pulled by the live drupal site.

This makes things really elegant.

However, I have noticed that a lot of developers tend to .gitignore all compiled code.

If it were a good practice, I would've loved to follow it, if and only if there wasn't this one issue: recompiling all the code that is needed in order for the theme to work out correctly.

This means that when I do a pull, I will have to recompile all the CSS and JavaScript code. Now, if I were to do a pull on the live site, there's a risk that a user goes to the site right at the moment I do the pull. No styles and scripts will be loaded on the user's end, so long as the code hasn't compiled.

Of course, compiling takes about a second, and the user might probably think to him/herself "meh, it was just my internet connection."

But there is also the issue that the server doesn't have the compilers installed to begin with. So now, I would do a pull, but there will be no styles, and no scripts.

Is it an absolute must that I delete all compiled code, or can I go ahead and include them in the commit?

答: MainMa's answer is great but it should be noted that this is a prime case for continuous integration. Setting up a machine (either a hosted solution or one of your own) that will identify when a commit has come in, compile the code, run appropriate tests, and build the deployment package if the tests succeed. This approach could be taken a step further and automate a scheduled deployment when your criteria for a deployment has been met.</p>

ContentLicense: CC BY-SA 3.0


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
When I first read the Design Patterns Book in 1995 or something it was a real eye-opener for me as a programmer.

Nowadays, James Shores' book about agile development inspired me a lot, and lately Lyssa Adkins about coaching teams, both of which are highly recommended if you are interested in such stuff.

ContentLicense: CC BY-SA 2.5


问:
How does agile work when replacing a working system?
In an ideal Agile world, you quickly build a small, but useful subset of the desired end system, and give it to users. They're excited, because it's useful, they start using it and give feedback. You then work out what to add on to it, build that, and repeat until you run out of time.

I've had a couple of projects recently that involved replacing some kind of working system. The above model just didn't work at all: until you'd built a system that included virtually all the functionality of the existing system, users had no interest at all. They wouldn't use it.

How do you apply Agile when "the smallest useful subset" is "all of it"?

答:
Releasing small increments into the world might work for greenfield projects but even then the small number of features might not be too useful.

Scrum advocates that after each sprint that the product is "Potentially Shippable". It does not have to be shipped but has to have the quality of a shippable product.

If you do want to give users an incremental version of the app then you can clasify it as Alpha then Beta then Release Candidate versions while still having the real Production app still being used.

You might find that new features get added and old ones get dropped if you are incorporating feedback from the users.


问:
Good practices for packaging Python programs
I've been using Python for a while now, both in the context of personal and professional projects.

One thing that occured to me recently is that I had never thought about a good way to deploy Python programs. Basically, since it's mostly a bunch of scripts, I usually just copy them to the machine where I want it deployed and voila !

But I believe there should be some good practices as to how you should deploy Python projects. I've heard about Python Eggs but not familiar enough with it to see if it's a good choice. Or a plain old tarball with a bunch of Shell scripts to run the core module scripts?

Basically I'd like to be able to do a nice, elegant and self-contained deployment, and not just copying files here and there, as it doesn't allow version tracking easily and it's quite messy.

答: Have a look at the Python package tutorial.  There are several ways described there: distutils and easyinstall are the main ones.  Note that some nix distributions will package things in their own format (.deb, rpm, etc) so you may look at those as well.</p>

ContentLicense: CC BY-SA 4.0


答:
Those of an Eastern bent may enjoy a cute little book of koans on the transcendent Tao of Programming.

This was my first step toward on the path toward enlightenment, and was the first thing that encouraged me to think about programming, and creative work in general, as an unconquerable entity of its own that exists to be discovered over time by the creator. Those who try to fight it or understand it will surely fail.

Title: What are some things you have read that inspired and guided you as a programmer?

Body: For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>


问:
Connecting mobile apps to a web service; What is it called and where do I start?
I have some basic knowledge of iOS development and I want to now start connecting my apps to databases hosted on the internet, so that users will have access to remote / public data that pertains to my app.

My problem is that after searching the internet for some advice, I realised I don't even know what this type of programming is called? From my perusing it doesn't even appear to have a common moniker, and this is making it really difficult for me to find any advice on how to even begin learning to connect my apps to a web database.

So my questions are, what on earth is this discipline called? And, how can I get started in learning it?

答:
Today the most common web services types are SOAP and REST. There are some iOS application that use .Net Web Services and you can create your own as per your requirement. You can use either Json or xml for getting data from database through webservice.

RestKit is a generalized framework for consuming JSON/XML over HTTP. It will interoperate with any backend, providing the payload can be expressed as key-value coding key paths.

Developing RESTful iOS Apps with RestKit

Database seeding. When the Core Data object store is used, you can seed a database from a collection of data files.

Ref:

REST Web Service for ResKit

Rest API Web Service - iOS

Backing Your iOS App With WCF JSON Web Services


问:
Can the Strategy pattern be implemented without significant branching?
The Strategy pattern works well to avoid huge if...else constructs and make it easier to add or replace functionality. However, it still leaves one flaw in my opinion. It seems like in every implementation there still needs to be a branching construct. It might be a factory or a data file. As an example take an ordering system.

Factory:

```<code>// All of these classes implement OrderStrategy
switch (orderType) {
case NEW_ORDER: return new NewOrder();
case CANCELLATION: return new Cancellation();
case RETURN: return new Return();
}
</code>```

The code after this doesn't need to worry, and there is only one place to add a new order type now, but this section of code still isn't extensible. Pulling it out into a data file helps readability somewhat (debatable, I know):

```<code><strategies>
   <order type="NEW_ORDER">com.company.NewOrder</order>
   <order type="CANCELLATION">com.company.Cancellation</order>
   <order type="RETURN">com.company.Return</order>
</strategies>
</code>```

But this still adds boilerplate code to process the data file - granted, more easily unit testable and relatively stable code, but additional complexity nontheless.

Also, this sort of construct doesn't integration test well. Each individual strategy may be easier to test now, but every new strategy you add is addition complexity to test. It's less than you would have if you hadn't used the pattern, but it's still there.

Is there a way to implement the strategy pattern that mitigates this complexity? Or is this just as simple as it gets, and trying to go further would only add another layer of abstraction for little to no benefit?

答: "Strategy" is about having to choose between alternative algorithms at least once, not less. Somewhere in your program someone has to make a decision - maybe the user or your program. If you use an IoC, reflection, a datafile evaluator or a switch/case construct to implement this does not change the situation.


问:
How relaxed (or not) should a sprint be?
What should be the attitude towards getting stories done that are assigned to a sprint? Obviously you want to prioritize getting them done in the sprint, but to me the whole point of agile is to be dynamic: You don't want to deliberately procrastinate or make it "ok" to miss finishing user stories in a sprint, but at the same time when unexpected things come up, and those stories do not get completed and are pushed to the next sprint, you don't want the feeling that you did something wrong. That shouldn't be a scary or negative experience, should it?

Are negative/scary experiences acceptable for missed sprint commitments?  Should developers be held accountable for missed sprint commitments when unexpected tasks come up that must be dealt with (Eg. production support)?

答:
When dosed correctly, stress is good. You want don't want to take away all stress, you just want to spread it out more evenly in time. Even when you play your favorite game, you will have some amount off stress and negative feelings. You actually get more energy out of it.

A team should genuinly feel bad about missed stories. It will give them energy to change something next time (work differently or plan less stories, both are good). They should also feel proud when they make their stories, of course.

You also mention unexpected tasks (production support). That raises a red flag with me. There should have been an agreed time box for all issues unrelated to the stories. Otherwise the game isn't fair, the team feels helpless and the negative feelings aren't used to improve.


问:
Setting Up a Development Environment
I am part of an organization that is formalizing their software development processes/capabilities/etc. While the organization is not traditionally a software organization, they want to do this right and provide the developers who work in the organization (which includes me) a solid set of tools in which to work from.

In particular, we are looking at standing up: source control, bug tracking software, documentation tools (for the developers - not for end-users), and, in general, project management software (continuous integration, project tracking, code review, software push). Some of the high-level requirements are:

Free is better. While we will consider purchasing tools, there is so much support in the FOSS community for development tools, I want to look there first.

Integration across systems. (For example, the bug tracking software should be able to link back to the source control.)

Easy to Import To and Export From. I do not want lock-in.

(Relatively) Easy to learn.

At this point, here is what I am looking at so far as my recommendations:

Source Control - Mercurial or Git - I am personally leaning more towards Mercurial based on my research and the fact that Mercurial appears to be easier to setup in our environment.

Bug Tracking - I'm at a loss here. I have used Bugzilla in the past, but, it makes me cringe when I use it.

Documentation - MediaWiki, Screwturn Wiki, Atlassian (of course, this costs money so that is not ideal)

I am looking for other suggestions of productivity tools/development tools that you have used. Please remember that we are a small organization, so I don't want to go over the top, but I do want to give developers good tools to use.

答:
I can suggest you Redmine .

Redmine is a flexible project management web application, that support these features :

Multiple projects support

Flexible role based access control

Flexible issue tracking system

Gantt chart and calendar

News, documents & files management

Feeds & email notifications

Per project wiki

Per project forums

Time tracking

Custom fields for issues, time-entries, projects and users

SCM integration (SVN, CVS, Git, Mercurial, Bazaar and Darcs)

Issue creation via email

Multiple LDAP authentication support

User self-registration support

Multilanguage support

Multiple databases support

As you can see from the feature list, it is a complete development environment that can be integrated with several SCM program, if you feel comfortable with Mercurial you can use Mercurial perfectly integrated with Redmine .

Personally i'm using Redmine from 2 years and i never found something similar in this area, it is simply the best !

Title: Setting Up a Development Environment


答:
Agile processes promote sustainable development.
The sponsors, developers, and users should be able
to maintain a constant pace indefinitely. - Principles behind the Agile Manifesto

If it's a scary or negative experience, and it happens all the time, you have a problem.   Software development should be fun.  Not negative or scary.

However, if the team is committing to finish some stories in a sprint and continuously not delivering, you also have a problem.  This problem is almost certainly not going to be solved by adding more pressure on the team to complete the stories.  If the problem is due to external factors, those need to be managed.  If the team is over-committing the ScrumMaster can guide the team towards committing to less story points.  There can be many reasons and each may need to be addressed differently.  An energetic and motivated team should have plenty of motivation to move forward.

Ideally whatever the problem is, it is raised during the retrospective, and fixed.

It shouldn't be that complicated for the team to figure out what they can accomplish during the relatively short period of the sprint and then accomplish it (an occasional story that gets pushed to the next sprint is OK, velocity can fluctuate, things change etc.).  If you can't get that going reasonably smoothly after a few sprints you're doing something wrong.

Title: How relaxed (or not) should a sprint be?

Body:
What should be the attitude towards getting stories done that are assigned to a sprint? Obviously you want to prioritize getting them done in the sprint, but to me the whole point of agile is to be dynamic: You don't want to deliberately procrastinate or make it "ok" to miss finishing user stories in a sprint, but at the same time when unexpected things come up, and those stories do not get completed and are pushed to the next sprint, you don't want the feeling that you did something wrong. That shouldn't be a scary or negative experience, should it?

Are negative/scary experiences acceptable for missed sprint commitments?  Should developers be held accountable for missed sprint commitments when unexpected tasks come up that must be dealt with (Eg. production support)?


问:
Is it good practice to comment with issue number?
I saw many issue numbers from comments of jQuery code. (Actually, there were 69 issue numbers in jQuery code.) I think it would be good practice, but I've never seen any guidelines.

If it is a good practice, what are the guidelines for this practice?

答: In general, I would not consider it good practice. But in exceptional cases, it can be very useful, namely when the code has to do something unintuitive to fix a complex issue, and without any explanation there would be a risk that someone might want to "fix" this strange code and thereby break it, while explaining the reasoning would result in a huge comment that duplicates information from the issue.</p>


问:
Write once, run anywhere. Is it still relevant?
Since Oracle bought Sun and Apple have decided not to continue developing their JVM, is the "write once and run everywhere" model still relevant or has web services/SOA reduced it to an edge case?</p>

答:
Write once, run anywhere always had a couple of problems:

"write once, debug everywhere": developers coming from a particular platform would occasionally make unwarranted assumptions about how all platforms worked, e.g. that configuration could always be stored in a registry, that all execution environments have virtual memory, or that all mobile phones that claim to support JPEG can actually render JPEGs. So in fact you would need to test your application on every platform you claimed to support, bringing the development costs back up.

"write once, run away": user interfaces in cross-platform apps tend to borrow the HCI paradigms of the platform in which the designer was most comfortable, and therefore don't fit well in the platforms to which they're ported. Even where the widget library has been engineered to produce native-looking controls (Apple, in particular, invested heavily in making Swing look native) the placement, behaviour and workflow can still be different.

On the server side these problems are less significant - the browser is the UI, and people tend to choose one of either Win or *nix and stay with it. In that instance, "write once, run anywhere" was what allowed numerous companies to ditch Solaris for Linux after the dot-com crash.


答:
You should look at the factors which makes your commitments fail and try to fix them. Large amounts of random events will keep messing up your sprints making your velocity unpredictable. Either fix the causes of this or introduce slack in your sprints. I prefer fixing.

Either way, the team cannot be held responsible if their job is disturbed by external factors. Use retrospectives to look into this.


问:
Sharing SCTP connection with multiple threads
I have an application that needs to run in SCTP environment, I have a question in sharing the connection among multiple threads for packet receiving only, I've tried with the sctp_sendmsg and it worked without even locking the threads (is that been taking care of by the OS, in other words, is it thread safe to do that). I've tested many cases with the send and I can't see them out of sync.

Anyway, back to the receiving, is it possible to create multiple threads and send each thread the sctp descriptor to start receiving messages? Do I need a lock here or is it ok without lock?

I'm using C in linux.

答:
So I created this quick test program which creates a UDP socket and then runs 2 reader threads and 1 writer thread, all using the same socket.  I used nc at the other end to make sure it was working.  It's not SCTP but it's BSD sockets, with which SCTP is mostly compatible and on which the enhanced SCTP api is based, so I would expect the behavior to be the same.

It behaves rather well - the sending thread doesn't block at all, and the two receiving threads receive each successive packets in an alternating sequence.

I wouldn't be surprised to see sendmsg() work without issue, but if you are using SCTP in stream mode and sending buffers bigger than the MTU this may not remain true.

But this is linux, I can't make any guarantees about how other OSes would behave.


问:
Real world usage of DelayQueue
What would be a real world usage of DelayQueue, what common problem it was designed to solve?</p>

答:
the main usage would be task timers like the for Timer classes

if one could make the delay independant from the system clock (which I beleive you can, not sure though) you can use it for game events like "after 5 ticks move to X" (otherwise clock jitter wold make this unreliable)

Title: Real world usage of DelayQueue


答:
In some cases, objects that you place on a queue should be on that queue for a certain amount of time before they are ready to be dequeued. This is where you use the java.util.concurrent.DelayQueue class, which implements the BlockingQueue interface. The DelayQueue requires that queue objects be resident on the queue for a specified amount of time.

For real world usage example see Minding the Queue article at devx site

...The real world example that I thought of to illustrate this (which might make you hungry) involves muffins. Well, Muffin objects (as we are talking Java—no coffee pun intended). Suppose you have a DelayQueue upon which you place Muffin objects... The getDelay method, in essence, states how much time is left for the object to be kept in the DelayQueue. When the number returned by this method becomes zero or less than zero, the object is ready (or in this example, baked) and allowed to be dequeued...

Since you don't really want to eat a Muffin that's not fully cooked, place the Muffin on the DelayQueue for the recommended cooking time...

Title: Real world usage of DelayQueue

Body: What would be a real world usage of DelayQueue, what common problem it was designed to solve?</p>


问:
Which style is better to check and log the error?
I have read some code and here are two ways to check and log the error in cpp code that repeats in my project many times. Which way is better?

1.

```<code>bool AClass::myMethod()
{
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         return false;
     }
    doSomthing();
    return true;
}
</code>```

2.

```<code>bool AClass::myMethod()
{
    if (SomeCondition())
    {
        doSomething();
    }
    else
    {
        Warning("AClass::myMethod： your description");
        return false;
    }
    return true;
}
</code>```

答: In my opinion, the first alternative is the clearly best. The normal scenario is to return true, and get to the doSomething, while the error logging can be looked at as a deviation of the normal scenario. In my opinion, these should resemble an exception, in that it is thrown/logged as the first thing that happens in the function. The latter alternative looks a bit messy in my eyes.</p>


答:
With such a short method, it doesn't matter much.

If the method would be long, then, well, one would better refactor it into shorter methods, up to the moment until, again, it wouldn't matter much which of your options to choose.

Actually, this could be a good criteria for when to stop refactoring: when different options begin looking "hard to choose from", "all roughly good enough", it's pretty safe to stop there.

I learned about that when studying Doug Lea's CPJ. While reading it, I noticed that in code snippets author uses a style I positively hate (else-after-return). I was planning to point this as a drawback in book review, but upon completion I discovered feeling uncomfortable about pointing finger at that. Since I usually prefer to be vocal about style issues, I thought what's wrong with me, got back and re-checked all the "bad" snippets. In that back-review, I noticed all the methods were pretty small (less than 10 lines or something), and particular style preference didn't matter much indeed.

Title: Which style is better to check and log the error?

Body:
I have read some code and here are two ways to check and log the error in cpp code that repeats in my project many times. Which way is better?

1.

```<code>bool AClass::myMethod()
{
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         return false;
     }
    doSomthing();
    return true;
}
</code>```

2.

```<code>bool AClass::myMethod()
{
    if (SomeCondition())
    {
        doSomething();
    }
    else
    {
        Warning("AClass::myMethod： your description");
        return false;
    }
    return true;
}
</code>```


答:
Which way is better?

The better is what is more understandable.

In my opinion, the first version, where the condition is not negated is better. Negating a condition makes the function more complex, therefore it is bit harder for understanding.


答:
I think that in this specific case, both solutions are equally well readable.

However, if there are other checks added later to verify that the function can continue to process, then only the first solution will be easily extended without making the code difficult to follow:

```<code>bool AClass::myMethod()
{
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         return false;
     }

     if (!SomeCondition2())
     {
         Warning("AClass::myMethod: another description");
         return false;
     }

    doSomthing();
    return true;
}
</code>```

is clearer than

```<code>bool AClass::myMethod()
{
    if (SomeCondition())
    {
        if(SomeOtherCondition())
        {
            doSomething();
        }
        else
        {
            Warning("AClass::myMethod： another description");
            return false;
        }
    }
    else
    {
        Warning("AClass::myMethod： your description");
        return false;
    }
    return true;
}
</code>```

So I would personally use the first version as soon as more than one check is necessary.

Body:
I think that in this specific case, both solutions are equally well readable.

However, if there are other checks added later to verify that the function can continue to process, then only the first solution will be easily extended without making the code difficult to follow:

bool AClass::myMethod()
{
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         return false;
     }

     if (!SomeCondition2())
     {
         Warning("AClass::myMethod: another description");
         return false;
     }

    doSomthing();
    return true;
}

is clearer than

bool AClass::myMethod()
{
    if (SomeCondition())
    {
        if(SomeOtherCondition())
        {
            doSomething();
        }
        else
        {
            Warning("AClass::myMethod： another description");
            return false;
        }
    }
    else
    {
        Warning("AClass::myMethod： your description");
        return false;
    }
    return true;
}

So I would personally use the first version as soon as more than one check is necessary.


答:
I humbly offer this as an alternate to 1 and 2:

3.

```<code>bool AClass::myMethod()
{
     bool valid = true;
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         valid = false;
     }

     if(valid)
     {
         doSomthing();
     }
     return valid;
}
</code>```

This is perhaps the most verbose of the three, but I think it is both clear and efficient, since in theory you shouldn't return in the middle of a method since it's not as fast.  Plus you can perform both specific and general failure code by performing actions in the initial validation phase and in the "else" of the if(valid) clause.

Better still, separate validation from the action by using two methods:

3.

```<code>bool AClass::isValid()
{
     bool valid = true;
     if (!SomeCondition())
     {
         Warning("AClass::isValid: your description");
         valid = false;
     }
     return valid;
}

bool AClass::myMethod()
{
     bool valid = isValid();
     if(valid)
     {
         doSomthing();
     }
     return valid;
}
</code>```

Body:
I humbly offer this as an alternate to 1 and 2:

3.

bool AClass::myMethod()
{
     bool valid = true;
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         valid = false;
     }

     if(valid)
     {
         doSomthing();
     }
     return valid;
}

This is perhaps the most verbose of the three, but I think it is both clear and efficient, since in theory you shouldn't return in the middle of a method since it's not as fast.  Plus you can perform both specific and general failure code by performing actions in the initial validation phase and in the "else" of the if(valid) clause.

Better still, separate validation from the action by using two methods:

3.

bool AClass::isValid()
{
     bool valid = true;
     if (!SomeCondition())
     {
         Warning("AClass::isValid: your description");
         valid = false;
     }
     return valid;
}

bool AClass::myMethod()
{
     bool valid = isValid();
     if(valid)
     {
         doSomthing();
     }
     return valid;
}


答:
Can the Strategy pattern be implemented without significant branching?

Yes, by using a hashmap/dictionary where every Strategy implementation registers at. The factory method will become something like

```<code>Class strategyType = allStrategies[orderType];
return runtime.create(strategyType);
</code>```

Every strategy implementation must register a the the factory with its orderType and some information how to create a class.

```<code>factory.register(NEW_ORDER, NewOrder.class);
</code>```

You can use the static constructor for registration, if your language supports this.

The register method does nothing more than adding a new value to the hashmap:

```<code>void register(OrderType orderType, Class class)
{
   allStrategies[orderType] = class;
}
</code>```

[update 2012-05-04]

This solution is much more complex than the original "switch solution" which i would prefer most of the time.

However in an environment where strategies changes often (i.e. price calculation depending on customer, time, ....) this hashmap solution combined with an IoC-Container could be good solution.

Body:
The Strategy pattern works well to avoid huge if...else constructs and make it easier to add or replace functionality. However, it still leaves one flaw in my opinion. It seems like in every implementation there still needs to be a branching construct. It might be a factory or a data file. As an example take an ordering system.

Factory:

```<code>// All of these classes implement OrderStrategy
switch (orderType) {
case NEW_ORDER: return new NewOrder();
case CANCELLATION: return new Cancellation();
case RETURN: return new Return();
}
</code>```

The code after this doesn't need to worry, and there is only one place to add a new order type now, but this section of code still isn't extensible. Pulling it out into a data file helps readability somewhat (debatable, I know):

```<code><strategies>
   <order type="NEW_ORDER">com.company.NewOrder</order>
   <order type="CANCELLATION">com.company.Cancellation</order>
   <order type="RETURN">com.company.Return</order>
</strategies>
</code>```

But this still adds boilerplate code to process the data file - granted, more easily unit testable and relatively stable code, but additional complexity nontheless.

Also, this sort of construct doesn't integration test well. Each individual strategy may be easier to test now, but every new strategy you add is addition complexity to test. It's less than you would have if you hadn't used the pattern, but it's still there.

Is there a way to implement the strategy pattern that mitigates this complexity? Or is this just as simple as it gets, and trying to go further would only add another layer of abstraction for little to no benefit?

Body:
Can the Strategy pattern be implemented without significant branching?

Yes, by using a hashmap/dictionary where every Strategy implementation registers at. The factory method will become something like

Class strategyType = allStrategies[orderType];
return runtime.create(strategyType);

Every strategy implementation must register a the the factory with its orderType and some information how to create a class.

factory.register(NEW_ORDER, NewOrder.class);

You can use the static constructor for registration, if your language supports this.

The register method does nothing more than adding a new value to the hashmap:

void register(OrderType orderType, Class class)
{
   allStrategies[orderType] = class;
}

[update 2012-05-04]

This solution is much more complex than the original "switch solution" which i would prefer most of the time.

However in an environment where strategies changes often (i.e. price calculation depending on customer, time, ....) this hashmap solution combined with an IoC-Container could be good solution.


问:
I have to run certain number of statements (which are executing .exe) in a loop
I have to run certain number of statements (which are executing .exe) in a loop.

```<code> ForEach(object obj in ListOfVersions)
    {
      Step 1: call Exe1 Args=obj.somevalues
      Log Step 1 completed for obj

      Step 2: call Exe2 Args=obj.somevalues
      Log Step 2 completed for obj

      Step 3: call Exe3 Args=obj.somevalues
      Log step 3 completed for obj
    }

Step 4: call Exe4
</code>```

Is there any specific design pattern available to use for above situation.

答:
There is no specific pattern in the general sense.  If you're referring to asynchronous operations, then the below answer is not what you're looking for:</p>

```<code>public void executeForAll()
{
    ForEach(object obj in ListOfVersions)
    {
      execute("Exe1", obj);
      execute("Exe2", obj);
      execute("Exe3", obj);
    }
    execute("Exe4");
}

public void execute(String executable)
{
    execute(executable, null);
}

public void execute(String executable, object obj)
{
    // Call executable Args=obj == null ? null : obj.somevalues
    log(executable, obj);
}

public void log(String executable, object obj)
{
    // Log Step 2 completed for obj
}
</code>```

Body:
There is no specific pattern in the general sense.  If you're referring to asynchronous operations, then the below answer is not what you're looking for:

public void executeForAll()
{
    ForEach(object obj in ListOfVersions)
    {
      execute("Exe1", obj);
      execute("Exe2", obj);
      execute("Exe3", obj);
    }
    execute("Exe4");
}

public void execute(String executable)
{
    execute(executable, null);
}

public void execute(String executable, object obj)
{
    // Call executable Args=obj == null ? null : obj.somevalues
    log(executable, obj);
}

public void log(String executable, object obj)
{
    // Log Step 2 completed for obj
}


答:
This class is perfect for a thread that wants to process multiple delayed events their proper order.

Suppose, for example, you have a display with 100 flashing lights, and all the lights flash at different unrelated rates.  You could have a thread for each light, or you could have one thread coordinate all of them using this class.  It would work something like this:

have a Light class with a flash rate

create an implementation of the Delayed interface that points to the light, say LightFlash

create your DelayQueue and add a new LightFlash for each light, with the delay set appropriate for the light's flash rate

loop:

get an event with DelayQueue::take().

toggle the light on/off

add a new event to the queue for the light's next flash with DelayQueue::put(E).

DelayQueue takes care of getting the next event to process.

Two real-world examples I can think of:

A (non-multithreaded) server that needs to perform certain timed actions, e.g. connection ping on each connection.

An implementation of a javascript-enabled browser, that needs to deal with the arbitrary number of timed events created with setInterval() and setTimeout().  Oh, and animated GIFs.

DelayQueue is probably implemented as a priority queue, which is generally best implemented as a heap.

Title: Real world usage of DelayQueue


答:
Note that the delays are associated with the elements that go on the queue rather than the queue itself.  Some objects that go into the queue could have a delay of zero, whilst some can have a much longer delay:

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Delayed.html

With this in mind, I can think of a few use cases - though they would probably be fragile and a bit of a code smell with regards to your messaging flow.  I'd use alternatives to all of them except in specific situations:

1) Control flow - we know that an order takes 60 seconds to process, so don't read the next order off of the queue until the object has been there for at least 60 seconds.

2) Message flow - A highly asynchronous system where we send off requests to 2 or 3 external services and then release the next task to process the order N seconds later once we know the first batch of jobs will at least have had a chance of completing.

3) Message batching - maybe orders of a certain type are bursty, so lets not process orders received in the last N seconds so we can see if similar orders come in shortly after that can be processed as a batch on the next run.

4) Message priorities - different messages or different customers could get a slightly higher quality of service with a lower or zero delay.

Title: Real world usage of DelayQueue


答:
I completely disagree with the other posters here!

Code comments with tracking references can be a huge help for maintenance programming.

If I'm tracking down a bug and getting close to the area of the code, to see that it has recently been changed and have a link off to the context of the change is a god-send.

Yes we have source code control, but it can be quite slow to check files and modules individually.  You want these things to jump out at you for recent changes.

I would probably deprecate them as I see really old ones in the code base, but there is very little down side to keeping more recent ones in and lots of potentially saved developer time if you use them smartly.

I actually think these little references to your bug tracking system are preferable to detailed comments in the code.

Title: Is it good practice to comment with issue number?

Body:
I saw many issue numbers from comments of jQuery code. (Actually, there were 69 issue numbers in jQuery code.) I think it would be good practice, but I've never seen any guidelines.

If it is a good practice, what are the guidelines for this practice?


答:
I agree with @Neil saying that there looks to be no special pattern name for this processing type. The name I would give for it is "Batch Processing Job" with each call representing a step in the batch. This naming is frequently used in some ETL Tools and Mainframes.

Notice the following though:

You need to decide whether you keep all the logs in one file or not. If you intend to, you have two options, either to use separate files and concatenate at end of all processes or to use one stream writer and keep it open until all processes finish then flush it and close  in all cases (even when one process fails).

You need to do error checking after each call.

Body:
I have to run certain number of statements (which are executing .exe) in a loop.

```<code> ForEach(object obj in ListOfVersions)
    {
      Step 1: call Exe1 Args=obj.somevalues
      Log Step 1 completed for obj

      Step 2: call Exe2 Args=obj.somevalues
      Log Step 2 completed for obj

      Step 3: call Exe3 Args=obj.somevalues
      Log step 3 completed for obj
    }

Step 4: call Exe4
</code>```

Is there any specific design pattern available to use for above situation.


问:
Does the use of Comparator interface breaks encapsulation in Java?
According to the essay "The Object Calisthenics" by Jeff Bay in the book ThoughtWorks Anthology,
Use of Getters and Setters should be avoided as they break encapsulation and we should instead ask the object to do something for us instead of digging in to the object and getting its fields.

how about comparison of objects ?

I have to find best object say a Resort for the customer on the basis of a rule that uses few properties of the Resort object.

This rule can change in future.
So I find use of comparator interface better as compared to comparable interface.
But then I will have to use getters and setters for to access individual properties to compare to objects in a different class.

答:
Books can be wrong or misleading. It is certainly true that having getters and setters for every field provides little more encapsulation than having those fields be public, and it's unfortunate that this kind of design is very widespread.

But it's nonsense to conclude that getters and setters should be avoided altogether. Instead, they should be added deliberately where appropriate, as part of the API design of the class:

If everything a field does can be handled by domain-specific methods, don't have a getter or setter - this is the best case.

If the value of a field is by itself useful and necessary for other classes, add a getter (not a setter)

If the fields represents something like a configuration value, a way for the behaviour of the object to be influenced from outside, add a setter (and a getter iff knowing this configuration could also be useful to other classes).

A Comparator could be seen as an example for case 2, especially if the Comparator is deliberately used instead of having the class implement Comparable. This indicates that the comparison logic is external to the class, and it depends on the field, so the field is useful outside the class.

A compromise might be to have a package private (default visibility) getter and keep the comparator in the same package - or even have it as an inner class that accesses the private field. That would be appropriate if you want the class itself to offer a choice of different sort orders.

If your only concern is that the sort order may change globally in the future, I'd actually stay with Comparable - it's still a change in once place, no need to separate it artificially.


答:
I think it's good practice to refer to an issue for further reading, while giving a short explanation in the comment itself.

I generally only add comments if there is something subtle or unintuitive in that piece of code. Since some subtle issues can't be explained completely in a few lines, and I don't want to add dozens of lines of comments, I'd add a short comment describing what this is trying to achieve, and refer to the issue for details.

For example:

```<code>// Verify MAC before checking the padding, to avoid padding oracle attacks
// See issue 123 for details
</code>```

Where issue 123 describes how that attack might look like, and why the new code is immune to the attack.

Or:

```<code>// Using foo's algorithm here, since it fits out usage pattern best
// Check issue 345 for a discussion of possible algorithms, and why foo was chosen.
</code>```

The main problem with putting issue numbers into your source is that you now have an external reference. So you need to be sure that you won't lose the issue.

Body:
I think it's good practice to refer to an issue for further reading, while giving a short explanation in the comment itself.

I generally only add comments if there is something subtle or unintuitive in that piece of code. Since some subtle issues can't be explained completely in a few lines, and I don't want to add dozens of lines of comments, I'd add a short comment describing what this is trying to achieve, and refer to the issue for details.

For example:

// Verify MAC before checking the padding, to avoid padding oracle attacks
// See issue 123 for details

Where issue 123 describes how that attack might look like, and why the new code is immune to the attack.

Or:

// Using foo's algorithm here, since it fits out usage pattern best
// Check issue 345 for a discussion of possible algorithms, and why foo was chosen.

The main problem with putting issue numbers into your source is that you now have an external reference. So you need to be sure that you won't lose the issue.


答:
These aren't the most fundamental things, but if I was starting from scratch I would definitely be looking at:

Cloud - something like Amazon Web Services for provisioning and running your environments.

Devops - automating and scripting building of environments in a repeatable way.

Vagrant & virtualisation - speeding up the provisioning of development environments.

Continuous Delivery - setting up your systems, processes, architecture etc such that you can automate and speed up releases and delivery with minimal downtime.

This type of stuff seems orthogonal to a development, but in my experience, can take up a lot of time and deliver a lot of value if you get it right.  It's also much easier to do if you are starting with a blank slate.

Title: Setting Up a Development Environment

Body:
I am part of an organization that is formalizing their software development processes/capabilities/etc. While the organization is not traditionally a software organization, they want to do this right and provide the developers who work in the organization (which includes me) a solid set of tools in which to work from.

In particular, we are looking at standing up: source control, bug tracking software, documentation tools (for the developers - not for end-users), and, in general, project management software (continuous integration, project tracking, code review, software push). Some of the high-level requirements are:

Free is better. While we will consider purchasing tools, there is so much support in the FOSS community for development tools, I want to look there first.

Integration across systems. (For example, the bug tracking software should be able to link back to the source control.)

Easy to Import To and Export From. I do not want lock-in.

(Relatively) Easy to learn.

At this point, here is what I am looking at so far as my recommendations:

Source Control - Mercurial or Git - I am personally leaning more towards Mercurial based on my research and the fact that Mercurial appears to be easier to setup in our environment.

Bug Tracking - I'm at a loss here. I have used Bugzilla in the past, but, it makes me cringe when I use it.

Documentation - MediaWiki, Screwturn Wiki, Atlassian (of course, this costs money so that is not ideal)

I am looking for other suggestions of productivity tools/development tools that you have used. Please remember that we are a small organization, so I don't want to go over the top, but I do want to give developers good tools to use.


答:
Encapsulation is hiding implementation details from outer world, in order to make implementation changes transparent. The very notion of "outer world" assumes existence of some "inner world". But where are the boundaries? They do not always have to be identical to the class boundaries. Often several classes are tightly dependant and can be seen as monolithic programming entity, for example, arcs and nodes in a graph implementation. In such a case, it's ok to use not only getters and setters, but even direct access to fields of siblings classes.

In your case, use Comparator if you like it. To underscore the fact that it belongs to the same programming entity as the class being compared (Resort), you can make it a static class inside the Resort class. Then you'll be able to access private fields of Resort from the comparator.

Title: Does the use of Comparator interface breaks encapsulation in Java?

Body:
According to the essay "The Object Calisthenics" by Jeff Bay in the book ThoughtWorks Anthology,
Use of Getters and Setters should be avoided as they break encapsulation and we should instead ask the object to do something for us instead of digging in to the object and getting its fields.

how about comparison of objects ?

I have to find best object say a Resort for the customer on the basis of a rule that uses few properties of the Resort object.

This rule can change in future.
So I find use of comparator interface better as compared to comparable interface.
But then I will have to use getters and setters for to access individual properties to compare to objects in a different class.


答:
Object calisthenics is not meant to be taken as a series of rules on OO design, rather they are designed to provoke a new thought process. Taking your scenario for example, and working within the boundaries of Object Calisthenics, I might take an approach wildly different to what I normally would have taken..

```<code>enum ResortFacility
{
    Pool,
    Sauna,
    Gym,
    Daycare
}

class Resort
{
    private ResortFacility[] facilities;

    boolean HasFacility(ResortFacility facility)
    {
        return facilities.Contains(facility);
    }
}

class CustomerRequirements
{
    private ResortFacility[] requiredFacilities;

    public boolean AreMetBy(Resort resort)
    {
        return requiredFacilities.All(required => resort.HasFacility(required));
    }
}

// possible usage:
var customerRequirements = new CustomerRequirements(ResortFacility.Pool, ResortFacility.Gym);

var resortA = new Resort(ResortFacility.Daycare);
var resortB = new Resort(ResortFacility.Pool, ResortFacility.Sauna);
var resortC = new Resort(ResortFacility.Pool, ResortFacility.Gym);

customerRequirements.AreMetBy(resortA) == false;
customerRequirements.AreMetBy(resortB) == false;
customerRequirements.AreMetBy(resortC) == true;
</code>```

Again, whether this approach has sufficient value over a much simpler public property comparison is something to consider.

Body:
Object calisthenics is not meant to be taken as a series of rules on OO design, rather they are designed to provoke a new thought process. Taking your scenario for example, and working within the boundaries of Object Calisthenics, I might take an approach wildly different to what I normally would have taken..

enum ResortFacility
{
    Pool,
    Sauna,
    Gym,
    Daycare
}

class Resort
{
    private ResortFacility[] facilities;

    boolean HasFacility(ResortFacility facility)
    {
        return facilities.Contains(facility);
    }
}

class CustomerRequirements
{
    private ResortFacility[] requiredFacilities;

    public boolean AreMetBy(Resort resort)
    {
        return requiredFacilities.All(required => resort.HasFacility(required));
    }
}

// possible usage:
var customerRequirements = new CustomerRequirements(ResortFacility.Pool, ResortFacility.Gym);

var resortA = new Resort(ResortFacility.Daycare);
var resortB = new Resort(ResortFacility.Pool, ResortFacility.Sauna);
var resortC = new Resort(ResortFacility.Pool, ResortFacility.Gym);

customerRequirements.AreMetBy(resortA) == false;
customerRequirements.AreMetBy(resortB) == false;
customerRequirements.AreMetBy(resortC) == true;

Again, whether this approach has sufficient value over a much simpler public property comparison is something to consider.


答: Yes, but in web-realm (give or take a few browser quirks). As for desktops, the "write once, run anywhere" is pretty much irrelevant given that something like 90% computer users in the world are MS Windows users.</p>

Title: Write once, run anywhere. Is it still relevant?

Body: Since Oracle bought Sun and Apple have decided not to continue developing their JVM, is the "write once and run everywhere" model still relevant or has web services/SOA reduced it to an edge case?</p>


问:
Interpreting gprof profiling output
I am practicing algorithm and data structures. Therefore, I keep profiling my programs. Here is an example output from gprof:

```<code>Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ns/call  ns/call  name
 29.76      2.58     2.58                             _IO_vfscanf_internal
 14.30      3.82     1.24                             ____strtof_l_internal
 11.71      4.84     1.02                             memcpy
  7.84      5.52     0.68  8400000    80.95    80.95  insertorupdate
  5.94      6.03     0.52                             _int_malloc
  5.77      6.53     0.50                             round_and_return
  3.81      6.86     0.33                             _IO_sputbackc
  3.23      7.14     0.28                             strlen
  2.88      7.39     0.25                             __strcmp_ia32
  2.13      7.58     0.19                             __isoc99_scanf
  2.13      7.76     0.19                             fgets
  2.02      7.94     0.18                             _IO_getline_info
  1.27      8.05     0.11                             __mpn_lshift
  1.21      8.15     0.11                             __memchr_sse2_bsf
  0.87      8.23     0.08                             malloc
  ... rest ...
</code>```

But I found it hard to understand what this means. For example, my program takes a lot of time in standard functions, I guess it should be good, right? Because, if one of my functions were consuming most of the time, that could mean I was doing something wrong. But as I say, I am not sure if I am interpreting this correctly, so any suggesting or pointers reading this is welcome.

答:
In this case, what it's telling you is that (as it's currently written) your program is spending most of its time doing I/O. The top two functions both appear to be involved with simply reading data from a file.

The part that would (or at least might) be somewhat disturbing is memcpy being the third highest, consuming almost 12% of the time. This may also be (a more or less unavoidable) part of reading input, but if you're using it directly, you might want to take a look where and how much you're using it to see whether you can leave data in the same place more, and (for example) rearrange pointers to it rather than moving blocks of data around (but keep in mind that even at best this is only going to improve speed by less than 12%).

As far as data structures and algorithms go, this is telling you they're (apparently) fast enough to contribute little to the overall run time. The major place to look is the I/O. From the looks of things, most of the time is being spent in a call to fscanf (or one of its cousins) doing a floating point conversion. If you were concerned with overall speed (not just the algorithms you wrote) an obvious possibility would be to look at storing that data in binary format to avoid converting from string to binary.

Title: Interpreting gprof profiling output


问:
Why do people hesitate to use Python 3?
Python 3 was released in December 2008. A lot of time has passed since then but still today many developers hesitate to use Python 3. Even popular frameworks like Django are not compatible with Python 3 yet but still rely on Python 2.

Sure, Python 3 has some incompatibilities with Python 2 and some people need to rely on backwards-compatibility. But hasn't Python 3 been around long enough now for most projects to switch or start with Python 3?

Having two competing versions has so many drawbacks;  two branches need to be maintained, confusion for learners and so on. So why is there so much hesitation throughout the Python community about switching to Python 3?

答:
A big show stopper for me, which I don't think can be addressed by automatic translation, is integer division.  I have scientific codes that rely on x/2 giving x rounded down (when x is integer).

Python 3 wouldn't do that, but would give a .5 answer (for odd x).

I can't just replace all / in my code with // because sometimes I do float division, and so want the float behaviour.

So, for me to port to python 3, I'll have to trawl through tens of thousands of lines of code, checking every /, and seeing if I can figure out whether it should be / or //.

Title: Why do people hesitate to use Python 3?


答:
If I have an old rusted out car that I need to drive to get to work, and I go to the dealership to purchase a new car.  The model that I want is out of stock so they have to order it from the factory and it will be a little while before it comes in.

The dealer then out of good faith decides to give you the cars engine block until the car you ordered has come in.  What are you supposed to do with a car engine?  Sure I can hook up some components to test it and make it works, but it really doesn't help get me to work tomorrow where the old rusted out car does.

Granted there is a far cry different between building a car and building custom software, but let's ignore that for the sake of argument.  The point of the story is not to be perplexed that the client finds no use for incremental changes when they already have software that is good enough to get the job done now.  It already fills their need for the time being.

That isn't to say that Agile is not an important part of the process here because it does allow for continuous feedback to the client on the status of the project.  They can ensure that progress is being made before major milestones and deliverables.  They can identify potential problems and issues earlier before it becomes too costly a mistake to fix.

Maybe as the car customer you just want to look at and evaluate the engine to make sure that you are indeed going to get what you anticipated.  Oops, I actually wanted a 6 cylinder engine instead of the 4 cylinder engine!  Didn't I tell you that earlier?  No problem, lets put a change into the factory order.

Sell the idea to the clients that it is in their best interest to use the new software releases not as a replacement just yet but to evaluate it and make sure that they are happy with each step along the way.

Title: How does agile work when replacing a working system?

Body:
In an ideal Agile world, you quickly build a small, but useful subset of the desired end system, and give it to users. They're excited, because it's useful, they start using it and give feedback. You then work out what to add on to it, build that, and repeat until you run out of time.

I've had a couple of projects recently that involved replacing some kind of working system. The above model just didn't work at all: until you'd built a system that included virtually all the functionality of the existing system, users had no interest at all. They wouldn't use it.

How do you apply Agile when "the smallest useful subset" is "all of it"?


答:
The agile solution might be not to replace all in one go, but to phase the replacement in gradually.

Introduce the new system gradually, bit by bit, keeping parts of the old system running. The old system isn't switched off all in one go, it just fades away. The new parts provide new functionality or other benefits, so the users are delighted to use them. This is also less risky, as you have a 100% working system at all times.

Read more from Martin Fowler.

The strategies in Michael Feather's Working effectively with legacy code can be useful


答:
I still think agile adds a lot of value in this scenario.

It's just that you have a very defined end goal of 'replace the current system.'

Agile techniques and processes can still get you there more effectively.

For instance:

You can still deliver on the system iteratively and in small sprints.

You can still use agile techniques to prioritise the work after communicating with the key people.

You can still use agile to plan based on observed velocity.

You can still use agile techniques and philosophies such as spreading knowledge, TDD, clean coding to enhance the quality and internal design of the project.

If you have people who are genuinely 'not interested' in the project and not engaging with the project until they have a perfect replacement, you have a bigger problem regardless of whether you are using waterfall, agile, or indeed any process.


问:
Completion time on a company where the supervisors don't know programming
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.

Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.

When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.

Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time.

I know this behavior is stupid, but how can I make them see the problem?

答:
Another approach would be to make it impossible for them not to see WHY/HOW you're giving the estimates.

Since you are responsible for the development process, why don't you track the team velocity and show them, based on your past iterations, why you won't make their deadline? I think it is simple: "our current speed is X, and we have Y story points for this iteration".


问:
Pattern for select case on object type (of interface)
I have read that doing a select case is often a code smell. There are cases however where an interface cannot solve my problem.

For instance, I have a set of date filter objects (last 7 days, last year, ect.) that implement a IDateFilter interface. In another part of the code, I need to determine the type of date filter so that the chart properties can be set. I may want to use a different chart tick interval for instance depending on the date filter.

The problem is I do not want to store this information in the date filter object as it is interface related and I do not want to couple the two.

How could a select case be avoided in this instance? Other than using select case on gettype or creating some enumeration for all the types and then exposing the type and doing a select case on that, I do not see a clean way to do this?

The decorator pattern comes to mind but even then I would still need a select case.

Any ideas?

```<code>if (type = last 7 days)
 set this property
else if (type = last year)
 set this property to something different
</code>```

I'm using asp net c# in case that makes a difference.

答:
The reason that select statements are consider a code smell is aresult of the Zero, One, Infinity rule aka there is no three.

Basically switch statements do two things which are "bad" -- first and foremost, they are an explicit list in your code, with the potential problems associated with that (maintaining sync, partial use, duplicated list for different properties of the same thing [i.e sometimes you do case x: b=y; and sometimes you do case x: c=z;]).

Secondly, if you add a new value or take it away, your code needs to be modified, and then deployed.

Both can be summed up with: code is a poor data structure.

OTOH, sometimes the worst is good enough (sort an array which always contains exactly two elements). So, as with all code smells it is a possible problem, and you need to examine the actual usage to see whether it is a problem.  The things to look for are size, varability, frequency of usage, and variations.


答:
Less than it was, it seems to me, certainly on the client. Javascript is constantly getting faster and more powerful and with the opportunities offered by HTML 5 there will be many more options for working in the browser in future ( or indeed now ) to do things that in the past would have needed some kind of client side software.

On the server it's less of an issue anyway I think- often enough I've used windows to develop Perl, PHP or Rails applications to run on linux or bsd servers and by and large they have worked fine. If you're working to a scripting runtime then you get similar platform-agnostic benefits to working on the JVM ( which is quite similar in essence ) without the typing overhead of working in Java.

I've experimented a bit with game development in Java and that is somewhere that write-once, read anywhere would be really handy, but actually once you need access to hardware accelleration you are no longer genuinely platform agnostic anyway....


问:
How does agile work when replacing a working system?
In an ideal Agile world, you quickly build a small, but useful subset of the desired end system, and give it to users. They're excited, because it's useful, they start using it and give feedback. You then work out what to add on to it, build that, and repeat until you run out of time.

I've had a couple of projects recently that involved replacing some kind of working system. The above model just didn't work at all: until you'd built a system that included virtually all the functionality of the existing system, users had no interest at all. They wouldn't use it.

How do you apply Agile when "the smallest useful subset" is "all of it"?

答:
Rather than re-writing the existing system (which as you mentioned will take quite some effort before the new system matches the existing functionality), consider the strangling vine approach. Basically, you implement new functionality using your new approach on top of the existing application. Eventually, as you address shortcomings of the old system to address new functionality, the new code will fully replace the old.

This requires more precision and effort than a "reboot" of the old app. But you get a shorter time to ROI. Also, going through the process, you can put hooks in place to enable the "new" system to be more easily strangled by the next "new" system.


问:
How to conduct a 3 days training on current techniques like TDD and CI
I am tasked to conduct a training for an upcoming team of 20 Java developers for a new project. The project owner wants us to use state of the art development techniques like TDD and CI. The developers are skilled Java developers but have minor to no experience with unit testing, and most likely only superficial experience in refactoring. So the overall project manager scheduled a 3 day training for all developers, and some project managers, to learn the "new" techniques, get everybody in a shared mindset and get started.

So I have 3 days (aka 20 hours) to teach them

Software Craftsmanship deleted due to answer

Unit Testing

TDD/BDD

Refactoring

Static Code Analysis

CI

Obviously I can't teach them everything. So my questions is

how to distribute the available time on these (and other) topics,

what to focus on and what do omit,

and how to best conduct a training session based on these topics?

答:
Day one:

Refactoring is at the core of all this, so I would start there. Explain about  code entropy and how you can use refactoring to fight that. Introduce DRY.

From refactoring, the next natural step would be to explain about unit tests, because you certainly need a safety net when doing refactoring.

Day two:

Training sessions. Form small teams and then give them some hairy code which they are asked to refactor. Then let the team compare results and discuss their findings. Or you can run a coding dojo to get some hands on experience with basic TDD. One quick way to set this up is with cyber-dojo online.

This day can be wrapped up with a discussion about software craftsmanship: when do we know that refactoring is complete? What is code quality? What is YAGNI?

Day three:

Talk about development feedback loops and how CI helps. Explain about automated builds and CI (which in essence, is just another feedback loop).

Don't forget to tie all it together with some overarching business helpers: being able to respond to change quickly and always working on the most important thing right now.


答:
Software Craftsmanship

Comes with experience. I'd exclude this from training.

TDD/BDD & Unit Testing

I would run these together and I would spend 2 days just on that. There is an awful lot to cover here. You have to demonstrate how you can guide design by tests (unit tests, integration tests and functional tests). You would also have explain how to configure/use mocking frameworks and custom matching frameworks such as nHamcrest

Refactoring

You can teach some re-factoring techniques, code smells, but I don't think that you can teach how to separate concerns. This comes with experience.

Static Code Analysis

Few hours to state its importance in CI process, how to run the analysis and how to interpret its feedback.

CI

I'd spend few hours explaining importance of CI in medium and large size organizations, but there is only so much you can teach. We have different people working on different aspects of CI and they have been doing it for many years. I don't think that you can "train" it in such a short period of time.

Title: How to conduct a 3 days training on current techniques like TDD and CI

Body:
I am tasked to conduct a training for an upcoming team of 20 Java developers for a new project. The project owner wants us to use state of the art development techniques like TDD and CI. The developers are skilled Java developers but have minor to no experience with unit testing, and most likely only superficial experience in refactoring. So the overall project manager scheduled a 3 day training for all developers, and some project managers, to learn the "new" techniques, get everybody in a shared mindset and get started.

So I have 3 days (aka 20 hours) to teach them

Software Craftsmanship deleted due to answer

Unit Testing

TDD/BDD

Refactoring

Static Code Analysis

CI

Obviously I can't teach them everything. So my questions is

how to distribute the available time on these (and other) topics,

what to focus on and what do omit,

and how to best conduct a training session based on these topics?


问:
GPL License - Selling and Stealing
I understand that when any software under the GPL is given to another the recipient has the same rights over the software that I do.  I also understand that this applies to "a work based on the Program".

Questions:

1)  I noticed several companies sell wordpress plugins and require that you buy a new plugin for each website.  Plugins are obviously "a work based on the Program".  How do they do this with GPL?  (ie I want to do this and not have someone take my plugin, turn around and sell it for themselves.  I'm working with Drupal, however, not Wordpress).

2)  If I write a module for in-house purposes and an employee takes that module home and puts it online, is that legal?  What I mean is that if someone steals my code do they still have the same rights over the code that I do?

3)  If I use Drupal modules in a software-as-a-service business and let people use it (ie hosted on my servers), do I still have to give them the source?

References:

http://www.gnu.org/licenses/quick-guide-gplv3.html

答:
The official wording is not "work based on", but "a derived work". A plug-in is not necessarily a derived work.

I can't imagine anybody being granted rights based on theft (or copyright infringement).

Title: GPL License - Selling and Stealing


答:
1) There is some disagreement over what exactly is "a work based on the Program", so those companies might simply use a different license and hope to win when and if they get sued by the Wordpress Foundation. Another possibility is to add some license key mechanism to the derived work and hope that most users won't bother hacking around it or getting it from someone who did. Another option is to sell a service contract together with the software.

2) The GPL only says that you have to give the full rights over the sourcecode to everyone whom you gave a copy of the software. That does not include people who just happen to have access to a server it's stored on. It might include people who work on the software itself (but I don't think so). In any case, most employment contracts would prohibit this anyway.

3) No. This is in fact the business model of many OSS-based companies, e.g. Github.

Title: GPL License - Selling and Stealing

Body:
I understand that when any software under the GPL is given to another the recipient has the same rights over the software that I do.  I also understand that this applies to "a work based on the Program".

Questions:

1)  I noticed several companies sell wordpress plugins and require that you buy a new plugin for each website.  Plugins are obviously "a work based on the Program".  How do they do this with GPL?  (ie I want to do this and not have someone take my plugin, turn around and sell it for themselves.  I'm working with Drupal, however, not Wordpress).

2)  If I write a module for in-house purposes and an employee takes that module home and puts it online, is that legal?  What I mean is that if someone steals my code do they still have the same rights over the code that I do?

3)  If I use Drupal modules in a software-as-a-service business and let people use it (ie hosted on my servers), do I still have to give them the source?

References:

http://www.gnu.org/licenses/quick-guide-gplv3.html


答:
That seems like a colossal amount to cover in 3 days. Barely enough time to overview the basics, and no time to cover specific tools nor the application of these techniques by your team on their projects. Moreover, a three day training session will take a lot of preparation by the presenter.

Have you considered following the training (or perhaps replacing it) with a series of regular lunch-hour (brown-bag) workshops to focus on practical details and practice?

1-hour workshops/seminars composed of a short presentation, a demo, and time for discussion are a really effective way to share knowledge. They are also much easier for the presenter to prepare!


答:
Many of these questions are answered in the Drupal Licensing FAQ.

I understand that when any software under the GPL is given to another the recipient has the same rights over the software that I do.

That's only correct if you didn't author the software in the first place.

If you did author the software, you hold the copyright to it by default. You can assign to others any rights you like, but unless you place it in the public domain (not possible everywhere) then you still have rights that anyone who is just licensing your software will not have.

Copyright holders will often dual license their software, providing a no commercial use public license and a commercial license. Often the former comes with no support, while the latter comes with a price tag and after sales service.

The problem with Drupal is that they assert that any Drupal modules constitute a derived work and thus must be licensed under GPL. While this may be the case for modules hosted on the drupal website, due to their terms and conditions, I am not convinced it is the case for software hosted elsewhere. Thanks kiamlaluno.

Plugins are obviously "a work based on the Program".

That's not always the case. Different projects handle these things differently. We have seen how Drupal judges this one way, but Eclipse has a different approach to plugins to their software. According to the Eclipse Public License FAQ:

Q: If I write a module to add to a Program licensed under the EPL and distribute the object code of the module along with the rest of the Program, must I make the source code to my module available in accordance with the terms of the EPL?

A: No, as long as the module is not a derivative work of the Program.

In other words, if you write a program that modifies the Eclipse framework then it must be covered by the Eclipse public license, but if you write modules which use the public interface of the framework, you can license it in any way you like.

In the case of a GPL program however, the situation is different:

Q: If a program released under the GPL uses plug-ins, what are the requirements for the licenses of a plug-in?

A: It depends on how the program invokes its plug-ins. If the program uses fork and exec to invoke plug-ins, then the plug-ins are separate programs, so the license for the main program makes no requirements for them.

If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. This means the plug-ins must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when those plug-ins are distributed.

If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case.

From Frequently Asked Questions about the GNU Licenses. Thanks Philip

If I write a module for in-house purposes and an employee takes that module home and puts it online, is that legal?

If you hold the copyright and they are using it in a manner not covered by the license attached to that software then they are guilty of copyright infringement. If they have been given access to GPL software then the software has been distributed to them and they can do anything allowed by the GPL.

As it is, you are probably covered by your employment contract with your employees. For contractors then you will probably need to talk to a lawyer about getting everyone to sign up to an NDA, if you haven't already. Thanks craig.

If I use Drupal modules in a software-as-a-service business and let people use it (ie hosted on my servers), do I still have to give them the source?

No, this is the so called application service provider "loophole" in the ordinary GPL that the AGPL was designed to plug.

Again, the Drupal specifically mentioned AGPL in it's licensing FAQ:

Q: I have found a module or theme in the contributions repository that says it is available under a different license than the GPL (including the LGPL or AGPL). What should I do?

A: Please file an issue in the Webmasters issue queue (specify "Licensing problem" for the component) and we will look into the matter.

You will have to be careful about AGPL modules sourced elsewhere though.

Title: GPL License - Selling and Stealing


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: Originaly Joel on Software, the way he writes made it very easy to grasp the concepts when I was beginning.</p>


问:
Is it ok to call external services or database inside the entity
I have "logic engine" which executes set of user configured steps. These steps are saved in the database as "Step" entities. The engine gets the first step and then executes steps until there are no more steps to execute:

```<code>public void Execute(details, data, Step firstStep)
{
    var step = firstStep;
    while (null != step)
    {
        step = step.Execute(details, data);
    }
}
</code>```

The different types of steps are expressed as derived classes. Each of them must implement the Execute method. The data and details parameters are used by the step to execute some logic. As fas as the logic engine knows it is just executing step after step without any knowledge what those steps do.

The problem:

Some of the steps need to access external services to get data or maybe even the same or different database where the actual step entities are stored. The information is usually used by other steps. One could say that some of the steps are just for loading data from external sources/database and other steps are using that data to make decisions. This separation is done so that we can use different data sources (as long as they produce the same kind of output to us) without the need to write any additional code.

Is there a better way to handle this type of domain? If I separate the actual Step and the logic (i.e. loading data from external service or from database) then my whole domain model (steps) doesn't have any logic. I would most likely have something like:

```<code>var handler = dictionary[step];
handler.Execute(step, details, data);
</code>```

Now the logic and any external dependencies are in the handler object but the actual domain object (step) is just a dummy place holder for the information. That doesn't sound right either.

答:
I suggest implementing a new object type, Step Data Source, in your domain. You can make it implement an interface so that the individual source won't matter so long the sources use the same interface. Just like you have different types of steps, you can have different types of StepDataSources. Since the steps are user-configured, you could even have a list of available data sources for the user to choose from (if that were a user story you wanted to implement).

Here's what a step that uses a step data source might look like:

```<code>public class DerivedStep : Step, IStepWithData
{
    ...
    public IStepDataSource IStepWithData.GetDataSource() { ... }
    public void IStepWithData.Execute(IStepDataSource DataSource, ...)
    {
        ...
        // use the data source to get the data to pass to Step.Execute
        var data = DataSource.SomeMethodWhichReturnsData(...)
        Execute(data, ...);
    }

    // overridden from Step parent class
    public void override Execute(data, ...)
    {
    }
}

// logic engine might do something like this
...
Step step = ...
if (step is IStepWithData)
{
    IStepWithData dataStep = step as IStepWithData;
    var source = dataStep.GetDataSource();
    dataStep.Execute(source);
}
else
{
    step.Execute(...);
}
...
</code>```

I'm not exactly clear on your domain, so that is just a stab at it. There are a lot of implementation details that are not shown obviously, and may not be exactly right for your domain.

I wouldn't worry too much about your classes not having "enough" behavior, and here's why; Your domain itself is of a transactional nature (users defining steps to execute on objects), so it's only natural for your domain model (code) to reflect that and become more transactional.

Body:
I suggest implementing a new object type, Step Data Source, in your domain. You can make it implement an interface so that the individual source won't matter so long the sources use the same interface. Just like you have different types of steps, you can have different types of StepDataSources. Since the steps are user-configured, you could even have a list of available data sources for the user to choose from (if that were a user story you wanted to implement).

Here's what a step that uses a step data source might look like:

public class DerivedStep : Step, IStepWithData
{
    ...
    public IStepDataSource IStepWithData.GetDataSource() { ... }
    public void IStepWithData.Execute(IStepDataSource DataSource, ...)
    {
        ...
        // use the data source to get the data to pass to Step.Execute
        var data = DataSource.SomeMethodWhichReturnsData(...)
        Execute(data, ...);
    }

    // overridden from Step parent class
    public void override Execute(data, ...)
    {
    }
}

// logic engine might do something like this
...
Step step = ...
if (step is IStepWithData)
{
    IStepWithData dataStep = step as IStepWithData;
    var source = dataStep.GetDataSource();
    dataStep.Execute(source);
}
else
{
    step.Execute(...);
}
...

I'm not exactly clear on your domain, so that is just a stab at it. There are a lot of implementation details that are not shown obviously, and may not be exactly right for your domain.

I wouldn't worry too much about your classes not having "enough" behavior, and here's why; Your domain itself is of a transactional nature (users defining steps to execute on objects), so it's only natural for your domain model (code) to reflect that and become more transactional.


问:
What constitutes a dead programming language?
Imagine you were elected coroner of IEEE or somesuch governing body and you had to pronounce a programming language as dead.  What signs would you look for?  Are there any zombie languages out there that don't know they're already dead?</p>

答:
People opinions determine the deadiness

Man walks into a hip, new geeky hi-tech area bar.

Man starts talking about cool features in COBOL.

People start backing away, giving you a wider and wider berth.

People are smirking all around

Man learns that COBOL seems pretty dead huh?

p.s. I was tempted to use 'woman' or person' instead of man but I don't want to imply that the [female] gender was related to it, was tempted to use 'person' but sounded weird given our history of "man walks into a bar" style jokes.  Well anyway, at least I'm thinking about the stuff.


答:
To read

books (both hyper inspirational, extremely educative, and deeply humbling):

Hackers: Heroes of the Computer Revolution, by Steven Levy

Dealers of Lightning: Xerox PARC and the Dawn of the Computer Age, by Michael Hitzlik

essays:

Teach Yourself Programming in 10 Years, by Peter Norvig

Many Coding Horror articles and posts

To view

11 part interview with Bill Gates and Steve Jobs on Youtube (The hosts are truly useless, but the guests are inspirational, obviously).

Sometimes it's more about people...

And a bunch of people on whose footsteps to follow, and on whose shoulders to stand (in no particular order and listed as they come to my mind now in free-flow): Alan Kay, Richard Stallman, Ken Thompson, Dennis Ritchie, Brian Kernighan, Theo de Raadt, Linus Torvalds, Eric S. Raymond, Rob Pike, Bill Gates, Steve Jobs, John MacCarthy, John Conway, Martin Odersky, James Gosling, Guy Steele, Donald Knuth, Edsger Dijkstra, John Carmack, Peter Molyneux... Either their own words and works were inspirational or their stories told by others. As long as you keep in mind that their skills and genius in some areas doesn't prevent them to be blind-sided by their own beliefs in others. Like anyone else. (The 2 books listed above will already cover them fairly well, for most of them!)

Or less famous but nonetheless active technologists that are interesting to follow from afar: Neal Gafter, Martin Fowler, Don Syme, etc...

I was inspired by the works of these people, and the things they did to achieve (or abandon) their projects.

Sometimes it's more about a culture and a dream, and breaking barriers...

Reading the 2600 as a kid when my English was embyonic, the story of early phreakers like Captain Crunch or the birth of the PC era with Wozniak at Apple and reading books and essays by William Gibson and Neil Stephenson were also inspirational for me as a programmer, though it didn't relate to programming directly. In that vein, even the Hacker's Manifesto, the Agile Manigesto or even things like the IEEE Code of Ethics were and still are inspirational.

Body: For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>


问:
Class fields/variables. Keep single reference point at class level or pass to individual methods?
Often I see a class where a value is injected into a method or even a constructor.  That value is then used by several methods within that class and a reference is simply passed through to each method that requires it.  To me this seems like a code smell, although I could very well just be a pedant.

Unless a variable is only required once within the scope of a single method, I would usually have a class level field that is initialised by the method that receives the value.  Any other methods would then reference this field if needed.  This seems to be a lot cleaner to me.

Thoughts?

答: It is a matter of ownership. If the class owns the value being passed in, or it can contain a shared reference to the (largely constant) value then the added coupling of having the class keep its own instance of the value makes sense. Otherwise, I would let the value be simply a parameter passed along. It decreases the coupling between the value and the class as well as being more friendly to unit testing and concurrent access.</p>


答:
Fields should store object state.  The lifetime of the fields should be the same as the lifetime of the object.  Do not use them as temporary storage to avoid passing transient values through a method chain.

There is a code smell, but adding a field to the existing class is not the proper solution.  Instead, factor out the related private methods into a separate class.  Then you can extract those method arguments into fields of the new class.

Instead of:

```<code>class A {
  int m;
  ... // other members;
  def f(x) { u = g(x); v = h(x); m = j(t1, t2); }
}
</code>```

write:

```<code>class F {
  int x;
  F(x) { this.x = x; } // constructor
  int f() { t1 = g(); t2 = h(); return j(t1, t2); }
}

class A {
  int m;
  ...
  f(x) { m = new F(x).f(); }
}
</code>```

This refactoring has the additional benefit of allowing F to be tested separately from A.

Title: Class fields/variables. Keep single reference point at class level or pass to individual methods?

Body:
Often I see a class where a value is injected into a method or even a constructor.  That value is then used by several methods within that class and a reference is simply passed through to each method that requires it.  To me this seems like a code smell, although I could very well just be a pedant.

Unless a variable is only required once within the scope of a single method, I would usually have a class level field that is initialised by the method that receives the value.  Any other methods would then reference this field if needed.  This seems to be a lot cleaner to me.

Thoughts?

Body:
Fields should store object state.  The lifetime of the fields should be the same as the lifetime of the object.  Do not use them as temporary storage to avoid passing transient values through a method chain.

There is a code smell, but adding a field to the existing class is not the proper solution.  Instead, factor out the related private methods into a separate class.  Then you can extract those method arguments into fields of the new class.

Instead of:

class A {
  int m;
  ... // other members;
  def f(x) { u = g(x); v = h(x); m = j(t1, t2); }
}

write:

class F {
  int x;
  F(x) { this.x = x; } // constructor
  int f() { t1 = g(); t2 = h(); return j(t1, t2); }
}

class A {
  int m;
  ...
  f(x) { m = new F(x).f(); }
}

This refactoring has the additional benefit of allowing F to be tested separately from A.


答:
If I use Drupal modules in a software-as-a-service business and let people use it (ie hosted on my servers), do I still have to give them the source?

No, you don't. Supposing that you are using a custom module, or a custom theme for your site, you are not forced to give them the source. As a matter of fact, there are two cases where the source code is not available:

Drupal.org, which runs on Pressflow 6, uses a custom theme (Bluecheese), but its code is not publicly available, and it is not even hosted on drupalcode.org (which hosts the GIT repository of all the projects hosted on Drupal.org). The code is maintained from some Drupal.org users (which are part of the Infrastructure team, as far as I know), but the code is not available to everybody.

Drupal Gardens, which offer site hosting based on Drupal 7, uses custom code, but the source code is not publicly available.

I don't think you are even obligated to reveal which Drupal modules are you using for the site you build to the users who use the services provided from your site.

Title: GPL License - Selling and Stealing


问:
Class Design -- Multiple Calls from One Method or One Call from Multiple Methods?
I've been working on some code recently that interfaces with a CMS we use and it's presented me with a question on class design that I think is applicable in a number of situations.  Essentially, what I am doing is extracting information from the CMS and transforming this information into objects that I can use programatically for other purposes.  This consists of two steps:

Retrieve the data from the CMS (we have a DAL that I use, so this is essentially just specifying what data from the CMS I want--no connection logic or anything like that)

Map the parsed data to my own [C#] objects

There are basically two ways I can approach this:

One call from multiple methods

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<MyObject> myObjects = GetMyObjects();
    // Do other stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    List<MyObject> mappedObjects = new List<MyObject>();
    // do stuff to map the CmsDataItems to MyObjects
    return mappedObjects;
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    List<CmsDataItem> cmsDataItems = new List<CmsDataItem>();
    // do stuff to get the CmsDataItems I want
    return cmsDataItems;
}
</code>```

Multiple calls from one method

```<code>public void MainMethodWhereIDoStuff()
{
    IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();
    IEnumerable<MyObject> myObjects = GetMyObjects(cmsDataItems);
    // do stuff with myObjects
}

private static IEnumerable<MyObject> GetMyObjects(IEnumerable<CmsDataItem> itemsToMap)
{
    // ...
}

private static IEnumerable<CmsDataItem> GetCmsDataItems()
{
    // ...
}
</code>```

I am tempted to say that the latter is better than the former, as GetMyObjects does not depend on GetCmsDataItems, and it is explicit in the calling method the steps that are executed to retrieve the objects (I'm concerned that the first approach is kind of an object-oriented version of spaghetti code).

On the other hand, the two helper methods are never going to be used outside of the class, so I'm not sure if it really matters whether one depends on the other.  Furthermore, I like the fact that in the first approach the objects can be retrieved from one line-- most likely anyone working with the main method doesn't care how the objects are retrieved, they just need to retrieve the objects, and the "daisy chained" helper methods hide the exact steps needed to retrieve them (in practice, I actually have a few more methods but am still able to retrieve the object collection I want in one line).

Is one of these methods right and the other wrong? Or is it simply a matter of preference or context dependent?

答: I don't think either approach is right or wrong. It's just a matter of preference. As you said, both methods are private and so it won't affect external usability. What's important is that it's clear what is necessary in order to accomplish the necessary task and it seems that both approaches are clear.</p>


答:
If the purpose of this method is to effect a state change, then it should either make the state change or throw an exception.  Log the problem when the exception is caught.  Also, as much as possible, avoid writing classes that can be in a state where some method calls are invalid.</p>

```<code>void AClass::myMethod(**args**) {
  if (!SomeCondition(**args**)) { throw new InvalidArguments(); }
  performAction(...);
}

try {
  AClass::myMethod();
}
catch (...) {
  Log(...);
}
</code>```

Body:
I have read some code and here are two ways to check and log the error in cpp code that repeats in my project many times. Which way is better?

1.

```<code>bool AClass::myMethod()
{
     if (!SomeCondition())
     {
         Warning("AClass::myMethod: your description");
         return false;
     }
    doSomthing();
    return true;
}
</code>```

2.

```<code>bool AClass::myMethod()
{
    if (SomeCondition())
    {
        doSomething();
    }
    else
    {
        Warning("AClass::myMethod： your description");
        return false;
    }
    return true;
}
</code>```

Body:
If the purpose of this method is to effect a state change, then it should either make the state change or throw an exception.  Log the problem when the exception is caught.  Also, as much as possible, avoid writing classes that can be in a state where some method calls are invalid.

void AClass::myMethod(**args**) {
  if (!SomeCondition(**args**)) { throw new InvalidArguments(); }
  performAction(...);
}

try {
  AClass::myMethod();
}
catch (...) {
  Log(...);
}


问:
Generate analog signal from Windows 7
I want to output an analog signal from my Windows 7 computer. The wave will be a combination of about 5 frequencies, with a maximum of 28 MHz. It won't be a problem to generate the wave data with C++, but I am not sure how to output the wave dynamically (as it is being generated). I am sure an audio port is not set up to output 28 MHz, but is there some way to bypass the sound card and interface directly with the port?

If not, what would be the easiest way to output a high frequency analog signal with C++?

答:
Look into professional hardware. For example National Instruments definitely provide generators that can output those frequencies, and are programmable via C+.

Audio cards are only capable of generating frequencies up to 20kHz.

Title: Generate analog signal from Windows 7


答:
Consider thread safety

In Java, all variables on the thread stack are isolated from other threads. This means that if the variable is passed in as a method parameter, or is scoped within a method, then it is immune from mutation by other threads. (This assumes that shared references are not being modified elsewhere such as would be the case if the variable was immutable like a String or Joda DateTime.)

This is not the case for field variables which may be mutated by other threads sharing the same object instance if appropriate handling is not in place (atomic operations, synchronization etc).

So, a common way to prevent this kind of side-effect is to keep state out of fields and only on the thread stack.