答:
I personally suggest Markov clustering.  I have used it several times in the past with good results.

Affinity propagation is another viable option, but it seems less consistent than Markov clustering.

There are various other options, but these two are good out of the box and well suited to the specific problem of clustering graphs (which you can view as sparse matrices).  The distance measure you are using is also a consideration.  Your life will be easier if you are using a proper metric.

I found this paper while looking for performance benchmarks, it is a good survey of the subject.

Title: Efficient graph clustering algorithm

Body:
I'm looking for an efficient algorithm to find clusters on a large graph (It has approximately 5000 vertices and 10000 edges).

So far I am using the Girvan–Newman algorithm implemented in the JUNG java library but it is quite slow when I try to remove a lot of edges.

Can you suggest me a better alternative for large graphs?


问:
Degree after BSc in Computer Science: Marketing, MBA, Techno-MBA, HCI?
Since a year I am a graduated Computer Engineer, and am now working in named field since 2 years. However, I'd like to get a Masters in a "softer" field and was thinking over the following choices:

MBA: Master of Business Administration, to bridge the business world with the world of computer science. Would give me an interesting job, travel potential, high salary etc.

Techno-MBA: Sort of an MBA, but aimed at people who already have a degree in Computer Science.

HCI: Human Computer Interaction degree, something I have been very interested in, but feel like it doesn't have the growth potential of MBA/Techno-MBA

Marketing: My most recent brainchild is a degree in Marketing, is this at all a good idea given my background? Growth potential?

Main priority: Gaining a skill, and gaining a job allowing me to use my social skills. Which path has the best "career potential"? (Controversial I know)

Any thoughts? Any feedback welcome.

Edit: DOH. Realized that the first sentence makes no sense. Was running my own semi-successful business during last year of school.

答:
Answer this question: "What do I want to be when I grow up?"

If you can honestly answer that question, your choice will be made for you.  Any job is only as good as long as something about it makes you happy, and that's not always (and rarely primarily) money.

ContentLicense: CC BY-SA 2.5


问:
What you should do if your junior did not adopt your suggestion?
I am leading a team of 3-4 junior developers. My job-- besides writing code-- is to provide supervision and guidance for the juniors.

But, I fully understand how much developers cherish autonomy in their work, and I don't want to destroy their intrinsic motivation by spoon-feeding them with my thoughts and my algorithms; I want them to explore the problem in their own ways, and think about it themselves and only come to me when they are really facing insurmountable issues.

When they do come to me, sometimes I would have to propose a completely different algorithm to solve the problem because their algorithm isn't robust enough ( remember, I am the senior and I have seen more than them). Of course I would explain this in a nice manner so as not to hurt their feelings, and I would gently outline how my solution is vastly superior than theirs, no condescending tone or condemning words.

But still, they are sometimes reluctant to accept my suggestion, partly because they have invested so much in their own algorithm, or partly because of the fear that using a new method would entail more learning time and make them appear to the management as if they are going nowhere. But deep in my heart I know very well that my algorithm is much better than theirs and they should just adopt it.

What should I do if they didn't adopt my suggestion? Should I just ask them to follow my way, or should I just let them have their heads banged on the wall many many more times and wait for them to come back to me? Doing the former makes me into a dictator, but doing the later would cost us precious development time and incur bug fixing cost. I am really in a dilemma here.

答:
This is a perfect introduction to unit testing. If your junior devs have a solution, it should be testable. Have them produce a unit test to stress their code. Then review the unit test. If you can show holes in the test, then it is easy to have them rerun the test and see their solution break under the pressure.

That allows you to show them why your solution is better, gives you a unit test that you can reuse when the code changes, and gives the junior devs a valuable learning experience. And who knows, you might find out that their solution is fine.

ContentLicense: CC BY-SA 3.0


问:
Parent and child permission schemes
Which approach makes most sense to use, the destructive one or the non-destructive one? Does anyone have real-world experience with one, both or even a different approach?

Model

A permission scheme has a set of permissions linked to it. It can also have a parent from which it inherits permissions.

Destructive

Taking away permissions from a parent scheme also takes away those permissions in any child scheme.

Reason to use this: when later re-enabling those permissions for a parent scheme, they are not automatically re-enabled for child schemes.

Reason to not use this: accidently taking away permissions from a parent scheme means the permissions for child schemes have to be restored separatly.

Non-destructive

Taking away permissions from a parent scheme has no effect on child schemes. The parent and child schemes are combined to determine the correct permissions.

Reason to use this: accidently taking away permissions from a parent scheme does not require the child schemes to be restored separatly.

Reason to not use this: when later re-enabling those permissions for a parent scheme, they are automatically re-enabled for child schemes.

答:
Normally what I have seen done is a combination of both in the following manner:

Parent scheme has a set of permissions

Child scheme has a set of permissions of which a subset is inherited from a parent.

If Child specifies a particular permission in its scheme the childs setting takes precedence over anything that might be inherited from a parent.

If Child doesn't specify a particular permission then the setting for this permission will be inherited from a parent.

Thus what will happen is that if the permission you are changing in the parent is used by the child without override you will override the permission for the child.

But if the child has it's own value for the particular permission the change in parent will have no effect on the child.

Title: Parent and child permission schemes


答:
I would question if you're actually presenting your suggestion in a way that isn't condescending.  When you're using phrases such as:

my solution is vastly superior than theirs

and

deep in my heart I know very well that my algorithm is much better than theirs and they should just adopt it.

it makes me think that you could be coming across with an attitude of "my way is superior".  No person likes being given that attitude.  When I've received it in the past, I've actively gone out of my way to use a different algorithm to prove the person wrong. It could be that your juniors are doing the same.

A better way should be to sit down with the person and discuss their algorithm.  Point out why you don't think it will work, and listen to the answers that they give you with an open mind. See if their algorithm can be modified to work correctly.

If what you junior has definitely will not work, then explain to them why it will not work.  What parts are incorrect, or will involve rewrites later on, or don't fit the business model.  Ensure that they have a good understanding of your reasons.  Then explain your algorithm to them, pointing out the pieces where it would work and their code would fail.

Title: What you should do if your junior did not adopt your suggestion?

Body:
I am leading a team of 3-4 junior developers. My job-- besides writing code-- is to provide supervision and guidance for the juniors.

But, I fully understand how much developers cherish autonomy in their work, and I don't want to destroy their intrinsic motivation by spoon-feeding them with my thoughts and my algorithms; I want them to explore the problem in their own ways, and think about it themselves and only come to me when they are really facing insurmountable issues.

When they do come to me, sometimes I would have to propose a completely different algorithm to solve the problem because their algorithm isn't robust enough ( remember, I am the senior and I have seen more than them). Of course I would explain this in a nice manner so as not to hurt their feelings, and I would gently outline how my solution is vastly superior than theirs, no condescending tone or condemning words.

But still, they are sometimes reluctant to accept my suggestion, partly because they have invested so much in their own algorithm, or partly because of the fear that using a new method would entail more learning time and make them appear to the management as if they are going nowhere. But deep in my heart I know very well that my algorithm is much better than theirs and they should just adopt it.

What should I do if they didn't adopt my suggestion? Should I just ask them to follow my way, or should I just let them have their heads banged on the wall many many more times and wait for them to come back to me? Doing the former makes me into a dictator, but doing the later would cost us precious development time and incur bug fixing cost. I am really in a dilemma here.


问:
Date as software version number
Software developers don't typically use date as version number, though YYYYMMDD format (or its variances) looks solid enough to use. Is there anything wrong with that scheme? Or does it apply to limited 'types' of software only (like in-house productions)?</p>

答:
Some good answers here already, but I would like to point out a case where using dates makes perfect sense: small libraries or snippets of code where the code is likely to be updated frequently but in tiny bits with no single version differing drammatically to the previous one.

In other words I'm talking about situations where there's no actual "version number" but basically a sort of quasi-daily repository dump.

When I come across this kind of stuff I usually welcome the choice as it's more useful for me to know that I'm using a relatively current script/lib rather than a specific version.

Title: Date as software version number


问:
Sending Data to a Specific Android Device
I am planning an application that includes a membership card functionality, where the user can place an order, either in the application or by phoning the vendor.  Once the order is placed, especially in the case of a phone in order, what would be the best approach to having the vendor side communicate relevant details to a specific device.

I have looked Android's C2DM, that doesn't seem to be the best method.  I don't want to send messages/data to all devices with the application installed, only the specific device that placed the order.

答:
Android's C2DM is device specific. So in your case, when user X initiates a phone order, your back-end could quite easily send the relevant data back to X's device (assuming you've verified that the person calling in is indeedX).

This data would not be broadcast to everyone who installed your app.


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

Passing an object to a constructor

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

Instantiating a class

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

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

答:
If your class doesn't expose the $config to external classes, then I'd create it inside the constructor.  This way, you're keeping your internal state private.

If the $config requires requires its own internal state to be set properly (e.g., needs a database connection or some internal fields initialized) before use, then it makes sense to defer the initialization to some external code (possibly a factory class) and inject it in the constructor.  Or, as others have pointed out, if it needs to be shared among other objects.


问:
Who does test-driven development?
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?

答: I do.  Its my preferred way of development, and I work for a large finance company who are happy for me to work in the way I see fit so long as I meet deadlines and produce quality code.  Done correctly, test first development need not take longer than test after development and let's not forget the other payoff's of test first development of less defects out of system testing later.</p>

Title: Who does test-driven development?


答:
Dates as a version number is good for marketing.  If people are using "Windows NT 5.0", they might not realize it's obsolete.  But if people are still using "Windows 2000", they'll instantly know it's a 12-year-old OS and be encouraged to upgrade.

However, it does make it harder to distinguish between "major" and "minor" updates.

Title: Date as software version number

Body: Software developers don't typically use date as version number, though YYYYMMDD format (or its variances) looks solid enough to use. Is there anything wrong with that scheme? Or does it apply to limited 'types' of software only (like in-house productions)?</p>


问:
How can I best prepare for building Windows Phone 8 Apps
I'm interested in learning to develop for Windows Phone down the road a bit, and am mostly interested in developing Metro Apps for the Windows Phone. It seems like there is some basic info for Metro development now, but no guidance on what will be relevant when Windows Phone 8 releases. There seem to be two potential strategies:

1) Start coding for Mango/WP7.5 and then later attempt to convert the experience for use with WP8. I guess this would involve learning Silverlight for applications (as opposed to XNA for games)?

2) Write Windows 8 Metro apps now with the dev preview. This experience seems less likely to be deprecated but it also seems harder to test in a real world fashion.

I'd normally lean towards option 1, but there are a few downsides with that route imo. First, I'd read elsewhere that Silverlight 5 was the last Silverlight release. I'm not completely clear on how much Silverlight experience will be useful for future iterations on their phone OS. Also, one thing I find interesting is the improved async/await setup and my understanding is that WP7 still relies heavily on callbacks for async operations.

I'm pretty unfamiliar with Silverlight/WP7/etc so please be gentle if there are some flagrant misunderstandings on my part. Thanks!

答:
If you want to write applications for Windows Phone then do so with what's in front of you now - if you structure your applications appropriately (use appropriate patterns i.e. MVVM) then you will be well placed to adapt to future changes - they're not going to cut current devs off at the knees (if anything MS have problem with not being nasty enough to legacy developers).

Taking a step back - there appears to be a lot of overlap between WP7 dev and Windows 8 Metro/WinRT development, the same sorts of rules and behaviours apply (notifications, isolated storage, etc, etc). And its XAML and C# and a set of .NET libraries (albeit a slightly different set for WinRT than for silverlight on and off the phone or for current WPF apps)

Everything has a finite lifespan - any development technology you learn now or any platform you target will, sooner or later, be substantially obsolete. That's why programming is about a range of skillsets not about coding in a given language on a given platform. You learn by doing and you never stop (you learn new things and adapt)


问:
What "version naming convention" do you use?
Are different version naming conventions suited to different projects? What do you use and why?

Personally, I prefer a build number in hexadecimal (e.g 11BCF), this should be incremented very regularly. And then for customers a simple 3 digit version number, i.e. 1.1.3.

```<code>1.2.3 (11BCF) <- Build number, should correspond with a revision in source control
^ ^ ^
| | |
| | +--- Minor bugs, spelling mistakes, etc.
| +----- Minor features, major bug fixes, etc.
+------- Major version, UX changes, file format changes, etc.
</code>```

答:
Here is very fine-grained approach to version numbering:

N.x.K, where N and K are integers. Examples: 1.x.0, 5.x.1, 10.x.33. Used for intermediate builds.

N.M.K, where N, M and K are integers. Examples: 1.0.0, 5.3.1, 10.22.33. Used for releases.

N.x.x, where N is integer. Example: 1.x.x. Used for support branches.

N.M.x, where N and M are integers. Example: 1.0.x. Used for release branches.

Here is the picture for simple illustration of version numbering approach:

PA means pre-alpha
A  means alpha
B  means beta
AR means alpha-release
BR means beta-release
RC means release candidate
ST means stable

Advantages of such version numbering approach are following:

It represents specifics of agile software development lifecycle.

It takes into account specifics of source code repository structure.

It is self explaining for those who got used to the patterns. Every pattern represents different artifact. Such patterns can be easily parsed and used for other purposes, such as issue tracking.

Versioning patterns set, which basic for the described versioning approach can be used for gathering metrics and planning.

It is focused on the concepts of maturity and level of quality. Very often such version numbers as 1.0.0 are assigned without much necessity (when software is in deep alpha). Presented version numbering approach allows to establish several levels of maturity. In the simplest case it will have only two levels: intermediate build (N.x.K) and release (N.M.K). Release means that piece of software with full version number (N.M.K) has gone through some kind of quality management process within the supplier company/organization/team.

It is an evidence of agile nature of both development and testing.

Encourages modular approach to the software structure and architecture.

There is also more complex diagram representing versioning approach in details. Also you might find useful presentation slides describing transition to the versioning approach. Presentation slides also explain why it is important to stick to the same versioning approach throughout the whole life of the software project.

Personally my attitude towards using date version instead of real version numbers assumes that developers of the software with dated versions:

Know nothing about software development lifecycle. Development is usually agile and iterative. Version numbering approach should represent iterative nature of software development process.

Do not care about software quality. Quality control and assurance are agile and iterative. Just like development. And version number should be the evidence of agile and iterative nature of both development and quality control/assurance.

Do not care about architecture or idea of their application. Major version number (N in N.M.K) is responsible for both architectural solution and underlying principle of the application. Major version number N is to be changed accordingly to the changes in architecture or changes of major ideas and principles of its working/functioning.

Do not have control over their codebase. There is probably only one branch (trunk) and it is used for everything. Which personally I do not think is right as it encourages codebase to become one large garbage dump.

This approach might seem a little bit controversial, but I believe this to be most straightforward way of giving software appropriate version numbers.

UPD (Feb-2021): I have also created a web-site https://versioningright.com aiming to explain deeper principles of software versioning that remain hidden behind the scenes.

ContentLicense: CC BY-SA 4.0


问:
How should XML subtree manipulation be handled in a public API?
I'm working on an API whereby a specific call would replace a subtree of an XML document—rooted at some element—with another subtree.

The two options I'm considering for a response to this call are:

Return the DOM

Return the modified subtree

In the interests of developing a standardized, stable API, I'd like to get this right. Is there a best way to handle this type of scenario? What are the benefits and drawbacks of doing it one way over the other? Would it make sense to offer both these options to API consumers?

答:
There are three distinct parts.

API Method 1:  Locate a subtree, rooted at some element.

API Method 2: Build a modified subtree and return it.

API Method 3: Combine the first two API Methods into a composite API Method which locates and replaces a subtree with a modified tree.

You should offer all three.


答:
At some point you have to be in charge. You sound like you're making an effort to let them voice their opinions. Your suggestions may not be perfect. The other devs may not understand/agree with you. They probably don't agree with each other. If you are in charge, it's not a democracy. They knew that when they took the job.

If there are no situations where they must follow you, you don't deserve and serve no purpose as their boss. Change your role in the team to be a resource and not an authority if you don't plan on using it. At some point you have to ship the best code you can under the time constraints that are available and can't debate, research and debate again every line of code until the end of time.

Give the orders. Live with the consequences. Learn from experience. Respect is a two-way street. You're demonstrating it and they're not.


答:
The simplest thing to do is to couple ExampleA to Config.  You should do the simplest thing, unless there is a compelling reason to do something more complex.

One reason for decoupling ExampleA and Config would be to improve the testability of ExampleA.  Direct coupling will degrade the testability of ExampleA if Config has methods that are slow, complex, or rapidly evolving.  For testing, a method is slow if it runs more than a few microseconds.  If all the methods of Config are simple and fast, then I would take the simple approach and directly couple ExampleA to Config.

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

Body:
Consider these two examples:

Passing an object to a constructor

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

Instantiating a class

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

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


问:
Dealing with large amounts of web service requests and storing that data
I have a desktop application that sends a POST request to my website every 5 minutes. This post request can contain a variable amount of data about the PC sending the request, but typically it contains about 20-30 variables of information.

I'm storing all of this information in a MySQL table in a format like, RequestID|Field|Value. I want to be able to keep all of it so I can run trend reports over 24 hours, 48 hours, weeks, months, years, etc.

This could amount so something like 10,000 rows of data every day. That's 3 million rows of data a year.

I can imagine 20-30 people using my website and the database storing 100 million rows of data a year.

What is the best way to approach this kind of 'notification' service and scale it?

答:
Only send changes.

Since you're running trends, you don't have to send every 5 minutes. Maybe stash the data on the desktop and send when the user is not so busy. Try to keep it from getting too full.

Aggregate the data into some daily averages and then weekly or monthly. You can off-load old detail data into some other data source to file just in case you want to bring it back to run a new trend analysis/formula that requires details.


答:
Think of it like an incremental backup plan of sorts. Store the aggregated data then throw away the underlying raw data.

A table for the YEAR data, A Table for the MONTHS (1 for each month depending on your DB design I suppose), and so on. At each "level", once you have enough data to summarize, do so and throw that "raw" data away.

For each day, 24/48 hrs, month, year, etc. you'll have to decide a cutoff point for keeping the "raw" data from which that "summary level" was made. For example, are 5 month old daily records useful?

Title: Dealing with large amounts of web service requests and storing that data

Body:
I have a desktop application that sends a POST request to my website every 5 minutes. This post request can contain a variable amount of data about the PC sending the request, but typically it contains about 20-30 variables of information.

I'm storing all of this information in a MySQL table in a format like, RequestID|Field|Value. I want to be able to keep all of it so I can run trend reports over 24 hours, 48 hours, weeks, months, years, etc.

This could amount so something like 10,000 rows of data every day. That's 3 million rows of data a year.

I can imagine 20-30 people using my website and the database storing 100 million rows of data a year.

What is the best way to approach this kind of 'notification' service and scale it?


答:
It is a very complex question and there is no best universal solution, usually each implementation chooses the best approach according to its own specific needs.

I would recommend reading more about Role Based Access Control theory to get a better understanding and bigger picture of the impacts of each specific implementation.

Here is a list of sources you can find useful:

"The NIST Model for Role Based Access Control: Toward a Unified Standard"

"RBAC Standard Rationale"

Wikipedia RBAC overview

Kim Cameron's Identity discussion blog: http://www.identityblog.com/

As one of the approaches I can suggest is to manage your permissions/roles through groups membership. Each user can be assigned to any group.. each role can be assigned to any group. This will decouple roles from users and give you flexibility of adding/removing users without influencing others' permissions.

Title: Parent and child permission schemes

Body:
Which approach makes most sense to use, the destructive one or the non-destructive one? Does anyone have real-world experience with one, both or even a different approach?

Model

A permission scheme has a set of permissions linked to it. It can also have a parent from which it inherits permissions.

Destructive

Taking away permissions from a parent scheme also takes away those permissions in any child scheme.

Reason to use this: when later re-enabling those permissions for a parent scheme, they are not automatically re-enabled for child schemes.

Reason to not use this: accidently taking away permissions from a parent scheme means the permissions for child schemes have to be restored separatly.

Non-destructive

Taking away permissions from a parent scheme has no effect on child schemes. The parent and child schemes are combined to determine the correct permissions.

Reason to use this: accidently taking away permissions from a parent scheme does not require the child schemes to be restored separatly.

Reason to not use this: when later re-enabling those permissions for a parent scheme, they are automatically re-enabled for child schemes.


答:
I don't like this idea, for reasons already described by others. Just use the major.minor.bugfix scheme - there's a reason why most people do it this way.

But whatever you do: pick one version-naming scheme, and stick to it. Don't do it like Windows, where they change the scheme with every release. And don't do it like Android, where each release has an API version number (8), a version number that's intended for marketing (2.2) and a stupid name (Froyo).

Title: Date as software version number


问:
Could a singleton type replace static methods and classes?

Possible Duplicate:

  What is the difference between all-static-methods and applying a singleton pattern?

In C# Static methods has long served a purpose allowing us to call them without instantiating  classes.  Only in later year have we became more aware of the problems of using static methods and classes.

They can’t  use interfaces

They can’t use inheritance

They are hard to test because you can’t make mocks
and stubs

Is there a better way ? Obviously we need to be able to access library methods without instantiated classes all the time otherwise our code would become pretty cluttered

One possibly solution is to use a new keyword for an old concept: the singleton. Singleton’s are global instances of a class, since they are instances we can use them as we would normal classes. In order to make their use nice and practical we'd need some syntactic sugar however

Say that the Math class would be of type singleton instead of an actual class.  The actual class containing all the default methods for the Math singleton is DefaultMath, which implements the interface IMath.  The singleton would be declared as

```<code>singleton Math : IMath
{
   public Math
   {
      this = new DefaultMath();
   }
}
</code>```

If we wanted to substitute our own class for all math operations we could make a new class

MyMath that inherits DefaultMath, or we could just inherit from the interface IMath and create a whole new Class. To make our class the active Math class, you'd do a simple assignment

```<code>Math =  new MyMath();
</code>```

and voilá! the next time we call Math.Floor it will call your method. Note that for a normal singleton we'd have to write something like Math.Instance.Floor but the compiler eliminates the need for the Instance property

Another idea would be to be able to define a singletons as Lazy so  they get instantiated only when  they're first called, like

```<code>lazy singleton Math : IMath
</code>```

What do you think, would it have been a better solution that static methods and classes? Is there any problems with this approach?

Addendum

Some points have been raised, that one of the main benefits of static methods is having methods that are "stateless" and thus side-effect free to some extent from a concurrency point of view. I wholeheartedly agree that that's a valid point. However we're mixing two different issues and problems here: One is making some methods invokable and globally accessible without having to explicitly create an instance. The other is having methods that are stateless.

The second problem could be solved by method having something like a stateless keyword that similarily to static prevented them from calling this or perhaps do even more to enforce no side-effecs. With singletons rather than static classes and something like stateless classes and methods I think you'd have the following pro's and con's

Pro's

"Static" methods in other classes and
framework classes could easily be
designed to be overridable

Classes would be easier to test

Using instances instead of static classes means design patterns work better (things like factories)

No limitation on inheritance and polymorphism in contrast to static

Cons

Perhaps slightly worse performance?

Bad programmers will but everything in singletons to have them globally accessible    instead of using dependency injection, perhaps you should only be able to access singleton methods and not properties/fields to avoid global variables :)

?

Perhaps Math was a bad example, but imagine if the .Net string methods were inefficient, you could easily replace them with your own using this method. Or some third-party class has has a singleton method that you wanted to alter slightly, you could inherit and alter that method

答:
The question of interfacing and inheriting static classes kept me busy for a while, too, although on a theoretical level more than on a practical.

There are also a couple of questions on SO dealing with the subject.

Finally I worked out a solution that essentially consists of

the separation of the "real class" part and the "static class" part into 2 classes

a class attribute assigning a class its pseudo-static class

a (static) helper class retrieving and instantiating the pseudo-static class for a class

For more details, read this mini series on my blog.


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

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

答:
In many fields dealing with legal or regulatory requirements are a daily thing. Sarbanes Oxley compliance is critical for large businesses, health care organizations have to consider HIPAA, programming for state, local or federal government projects tends to have lots of regulatory requirements. You may also need to consider Government Accounting Standards to make sure you have what auditors need. You may have to deal with privacy considerations and there are laws about how the disabled must have ways to access the data.

In our business we have government regulations that vary by state that our clients must follow and spend a fair amount of time making sure the compliance rules are followed and in creating reports to show that we have complied with regulations. If you are selling anything, at a minimum you need to consider taxes. You may also get stuck dealing with things like ISO certification requirements which aren't legal, but are simliar in their pain in the posterior factor.

In general if you are doing business programming (especially anything to do with health care or finances) and you are unaware of any legal or regulatory requirements, you have a good chance of doing something wrong. If you (or your company) have never asked about them, then you are definitely doing something wrong as it should be one of the first questions that almost every project starts with. You don't know if the answer is no unless you ask.

If you are selling software to businesses (not so much individuals), regulatory compliance is often a key selling point as not everyone does a good job with this. We get a lot of our clients specifically because we do a much better job of this than our competition and regulatory compliance is critical for our clients.

If you are in Gaming, I would expect less of a need for this although, I'd bet there are still disability laws to comply with.

I personally have never worked on a major project that didn't have some regulatory or legal needs to consider.


答:
Without repeating good ideas from other answers, I have a problem in mind which wasn't addressed yet.

If you happen to do a fork, between an older version for backward compatibility, and a new version for an incompatible modernisation, you can't distinguish them via version numbers.

For example the Linux kernel was forked around the year 2000 into the old 2.4.x branch, which is probably still supported today and counts as 2.4.199, while the new version has been 2.6 for many, many years, and is 2.6.32 for older systems, but 3.2 for the newest kernels.

If you have documentation about your releases, you will double the information and tell the people, that version 20120109 arrived in 2012 at 01/09. Mh. But what, if there is a last-moment bug detection, and a release is delayed for a week, but the documentation, where the name is mentioned, is already ready, maybe printed, press information is out and so on. Now you have a discrepancy which is problematic, if version 20120109 arrived at 2012/01/13.

In SQL, the question whether IDs should carry semantic information has often been discussed, and the result is always: avoid it like hell! You're creating an unnecessary dependency. It can't be of benefit.

Ubuntu with its 04/10 scheme had its problem in 2006, when version 6.04 was delayed and became 6.06 . In year 3000 there will soon be the next problem! :)

Title: Date as software version number


问:
Should we test all our methods?
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

答:
I go by Kent Beck's rule of thumb:

Test everything that could possibly break.

Of course, that is subjective to some extent. To me, trivial getters/setters and one-liners like yours above usually aren't worth it. But then again, I spend most of my time writing unit tests for legacy code, only dreaming about a nice greenfield TDD project... On such projects, the rules are different. With legacy code, the main aim is to cover as much ground with as little effort as possible, so unit tests tend to be higher level and more complex, more like integration tests if one is pedantic about terminology. And when you are struggling to get overall code coverage up from 0%, or just managed to bump it over 25%, unit testing getters and setters is the least of your worries.

OTOH in a greenfield TDD project, it may be more matter-of-fact to write tests even for such methods. Especially as you have already written the test before you get the chance of starting to wonder "is this one line worth a dedicated test?". And at least these tests are trivial to write and fast to run, so it's not a big deal either way.

Title: Should we test all our methods?


问:
Maintainability of Boolean logic - Is nesting if statements needed?
Which of these is better for maintainability?

```<code>if (byteArrayVariable != null)
    if (byteArrayVariable .Length != 0)
         //Do something with byteArrayVariable
</code>```

OR

```<code>if ((byteArrayVariable != null) && (byteArrayVariable.Length != 0))
  //Do something with byteArrayVariable
</code>```

I prefer reading and writing the second, but I recall reading in code complete that doing things like that is bad for maintainability.

This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.  (The second part will throw an exception if evaluated with a null byteArrayVariable.)

I don't know if that is really something to worry about or not, and I would like general feedback on the question.

Thanks.

答:
I think the second form is fine, and also more clearly represents what you're trying to do. You say that...

I recall reading in code complete that doing things like that is bad for maintainability. This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.

It doesn't matter if all languages do that. You're writing in one particular language, so it only matters if that language does that. Otherwise, you're essentially saying that you shouldn't use the features of a particular language because other languages might not support those features, and that's just silly.


答:
Here's good way to think about quality of your software:

type checking is handling part of the problem.

testing will handle the rest

For boilerplate and trivial functions, you can rely on type checking doing it's job, and for the rest, you do need test cases.

Title: Should we test all our methods?

Body:
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?


答:
This made me think, though. Should we strive for the highest test coverage %?

Yes, ideally 100%, but some things are not unit testable.

getters and setters (unless they actually have some logic in them)

Getters/Setters are stupid - just don't use them. Instead, put your member variable to public section.

"boilerplate" code

Get common code out, and unit test it. That should be as simple as that.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

By not doing so, you might miss some very obvious bugs. Unit tests are like a safe net to catch certain kind of bugs, and you should use it as much as possible.

And the last thing : I am on a project where people didn't want to waste their time writing unit tests for some "simple code", but later they decided not to write at all. At the end, parts of the code turned into big ball of mud.

Title: Should we test all our methods?


问:
What are your advice, methods, or practices to take out the most from a day on-site at a customer?
We just deployed a large software that affects the way the user work-day looks like in many aspects. It changes a lot of things in the way they interact between eachothers.

The developers of the team are taking rounds and spending one day at the customer's site to understand better what is a typical day for our user, and the learning process they go through.

In this context, what How would you approach that day, what kind of questions do you ask, how do you observe the user. Are there defined practices that exist?

Also what wouldn't you do? Did you have some bad experience out of this?

答: I would shadow the user throughout their day.  Sitting with the user and observing how they use the system and what their workflow really is.  Ask questions about any aspect of their process that you don't understand by observing.  Its a good way to learn what users are really doing.</p>


答: Use semantic versioning - that way, you get some idea of the sort of changes being made between versions without having to inspect the code itself: http://semver.org/</p>

Title: Date as software version number


答:
What not to do:

Forget to tell those you are observing who you are and why you are
there. They will assume you are there for some bad reason like
determining if they should get fired if you don't explain.

Tell jokes. You don't know their corporate culture and what is
appropriate in the IT world is often vastly different thtn the rest
of the world. At best they won't think you are funny, at worst you
could have a sexual harrassment suit on your hands.

Be careful with scheduling, don't pick a day when they won't have
time to talk to you (such as when payroll is done if you are
observing the financial department.)

Don't get defensive if they criticize your application! There is a good chance it will be very humbling to hear how much they hate your product. Remember what is important to them often bears little resemblance to what is important to you.

What to do:

Take notes.

Ask if you can observe before observing someone. Not everyone feels
comfortable being observed. Ask the management to point you to a
relatively experienced person and a relatively new person and people
at different levels of the organzation or who have differnt functions
to observe. You want to see a broad group of users actually using the product. Never under any circumstances talk only to managers unless only managers use your system. Managers do NOT know how users use the system but they think they do.

Ask them what parts of the application that they find awkward or
difficult to use

Ask them what they like

Ask them where they typically experience performance problems

If they enter data from paper forms, get blank copies if at all
possible - it helps if the user interface is designed to follow the flow of the form.

Ask them if there is something they still have to do manually (by this I mean using something other than your application) because
the application doesn't do it. Also look for them doing such things
while you observe. Particularly note if you see them doing something
manually that the applciation actually should do. That may mean a
pain point - a place where it is easier to use an Excel spreadsheet
than use your application.

Observe for awhile before you start asking them questions. Note
questions as you observe, you will probably find other things you
want to ask.

If there appear to be performance problems you were unaware of, find
out the stats on their systems (then you can build a test system that
is a similarly slow machine using the same operating system) and time
some of the tasks that seem to be taking so long. In fact do this even if you don't have performance problems right now. It helps to see exactly what operating sytems, internet browser they use as well as how fast in general their machines are.

Be unobtrusive while observing - they should know you are there and
why, but then stay out of their way. You will get better data about
what they do after they forget you are there.

Ask for more detail after they tell you something. Often the first
answer is far from the real answer. People forget to mention details
that are critical to you. Don't forget to ask about edge cases. If
they tell you they then send this to be approved, find out what
should happen when it isn't not just when it is.

When they describe a problem, ask if they can show you. Often they
will miss parts of the process or will not understand how something
is done. This can help with the user documentation and training.

If you get time, show them what you need from them when they report a
bug. This can improve your bug reports greatly.

(Can you tell I spent almost 15 years collecting this kind of data on processes?)

Title: What are your advice, methods, or practices to take out the most from a day on-site at a customer?

Body:
We just deployed a large software that affects the way the user work-day looks like in many aspects. It changes a lot of things in the way they interact between eachothers.

The developers of the team are taking rounds and spending one day at the customer's site to understand better what is a typical day for our user, and the learning process they go through.

In this context, what How would you approach that day, what kind of questions do you ask, how do you observe the user. Are there defined practices that exist?

Also what wouldn't you do? Did you have some bad experience out of this?


答:
I find them both readable, and I do not accept the argument that you should worry about code maintainability if you were to switch languages.

In some languages the second option performs better so it would be the clear choice then.

Title: Maintainability of Boolean logic - Is nesting if statements needed?

Body:
Which of these is better for maintainability?

```<code>if (byteArrayVariable != null)
    if (byteArrayVariable .Length != 0)
         //Do something with byteArrayVariable
</code>```

OR

```<code>if ((byteArrayVariable != null) && (byteArrayVariable.Length != 0))
  //Do something with byteArrayVariable
</code>```

I prefer reading and writing the second, but I recall reading in code complete that doing things like that is bad for maintainability.

This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.  (The second part will throw an exception if evaluated with a null byteArrayVariable.)

I don't know if that is really something to worry about or not, and I would like general feedback on the question.

Thanks.


问:
Development setup for TDD. Is it correct?
This is how my team has it's development environment set up:

Each team member has a local development environment on their own computer, where they check out the code from a shared repository.

Every developer work in their local development environment, once they finished writing the code they commit back.

The code is then checked out to a staging/testing server with the same environment setup

If everything is OK, it will be pushed to a production server.

We're trying to integrate unit testing and BDD (behavior driven development) into this setup and we'd like to use a continuous integration server (Jenkins) too.

My question is where should we install this and where should we test the code?

Install the full testing stack for each developer: TDD tools + BDD tools + Jenkins?

Install the test tools only on the staging/testing server and only test code here once each developer made his/her code commit?

How is your setup?

答: If you're really doing TDD, the developers are writing and running tests locally, so you definitely need the testing tools on each developer machine.</p>

OwnerDisplayName: feketegy


答:
Installing a CI (Jenkins in your case) on every single workstation would be an overkill. This thing is pretty heavy! Common practice is to have it only on one server and make it check for modifications (commits) in the repository every X minutes (so it automatically builds) - or you can make a post-merge hook in your VCS to trigger a build.

What do you mean by testing tools? Every dev should be able to run unit/integration tests from his environment if that is what you are asking about. In fact it is a good practice to run tests before you commit (I know that the CI is there to check it anywhere but still I prefere not to crash the builds).

The setup at all the companies I worked was pretty similar:

everyone has its own local dev env where he can run unit/integration tests if he wants to

there is obviously a common VCS repository where we all commit

there is a CI on a server somewhere polling for new commits from the VCS repo and if it finds one it starts a CI job building the whole project checking for any failures (build or test ones).

we had a nightly build for each project which would build the application from the latest sources from the repository and deploy it to the server in the middle of the night when no one is using it.

You can go even further and try to adopt continuous deployment. We do not have that at my current job since the procedures of deploying the application are very corporation-like.

Nice things to have:

mails incoming after every build (saying it either succeeded or
failed, always send a mail, if you want not to send one after a
successful build it is a mistake since you don't know if the build
was triggered or not)

a screen in a visible to all/most developers place with the current state of all your builds

Title: Development setup for TDD. Is it correct?

Body:
This is how my team has it's development environment set up:

Each team member has a local development environment on their own computer, where they check out the code from a shared repository.

Every developer work in their local development environment, once they finished writing the code they commit back.

The code is then checked out to a staging/testing server with the same environment setup

If everything is OK, it will be pushed to a production server.

We're trying to integrate unit testing and BDD (behavior driven development) into this setup and we'd like to use a continuous integration server (Jenkins) too.

My question is where should we install this and where should we test the code?

Install the full testing stack for each developer: TDD tools + BDD tools + Jenkins?

Install the test tools only on the staging/testing server and only test code here once each developer made his/her code commit?

How is your setup?


答:
Our setup:

Each developer has a their own dev server (vm)

so all developers can develop on the same version of the same OS, with the same set of system packages installed

so there isn't 1 shared def platform to make sure system updates or toolchain updates don't impact everyone until they have been vetted.

to support homogenous development vms, but heterogenous development tools (whatever dev tools make each developer most productive)

which is on the same secured network (accessible only through VPN/2-factor auth) as the large (shared) systems we integrate with

to be on the same OS version and configuration as the platform that software will be deployed to in production

Each developer does TDD, but writes automated acceptance tests, not unit tests

assures testing of integration points

trades off some assurance in component correctness for overall system correctness

requires less time to do large refactors because we don't pay for test updates on refactors

Each developer has a toolchain, and the codebase.  The test suite is part of the codebase.

to reduce bug vectors by assuring that everyone is working with the same versions

CI server is created the same way as a dev server, with the same dev environment. It runs with every commit, executes tests, tags code and produces installable packages

to assure the test suite is run against every commit

to assure every successful build is tagged and packaged since it is considered an RC

to assure all RCs are built the exact same way every time

to assure that packages are created the same way every time

Packages are installed in QA for more extensive testing

our tests significantly reduces, but doesn't completely eliminate the need for manual testing

The same packages that pass QA are installed in Production

to reduce bug vectors by using the exact same bits that were already extensively tested


问:
What issues do I need to consider when setting up a User Support group for a large enterprise system?
I have been tasked with becoming the Administrator for a large enterprise software system that consists of several shrink wrapped applications and some home grown 'glue' and has a couple of hundered users across three continents.

What do you think are the aspects / points I need to address?

At the moment the best I can come up with is a quote from Kathy Sierra's Creating Passionate Users blog post:

How does this help the users kick ass?

which seems helpful as a mantra, but not very concrete.

答:
I'm assuming here that your User Support Group is some kind of online community/forum/portal that you're pointing your users to if they have a problem or query about something your company supports.

I'd suggest that you put yourself in the shoes of one of your users (or maybe even sit down with a few of them) and step through their user cases/stories/epics (or whatever terminology you want to use).

You'll also need to take into account the technical ability of your users. The less experienced they are, the more you have to be proactive about the support you give.

For example...

Scenario: A user gets an error message when they click a button in one of your applications and they can't work out how to fix it. Googling doesn't provide an answer.

User navigates to your site

How does the user know where to go? Is it a message in the program or does it come up from the help menu? Is it an easy to remember URL?

User logs in

How are accounts created? Automatically?

If accounts are not created automatically, how easy is the sign-up process? Do they have to give you their SSN/Name of first pet/What they ate for breakfast or is an email address and password enough (and if so, are you only going to let specific email addresses sign up for confidentiality?)

Once logged in, it's hard to predict what the user will try and do. All you know from the scenario is that they want an answer to a problem.

If they are clear about which program is causing them to visit your site in the first place, do each of your programs have a FAQ?

Is the FAQ well-written and from a user point of view (not a developer point of view)?

Is this FAQ frequently updated?

Do you have a search functionality?

Does it pull information from all areas of your site? (FAQs, forums, tickets, etc.)

Does it presents the results in an easy-to-read display?

Is there a forum where people can post issues, queries or suggestions?

Is this community-driven or vendor-driven?

Do people get responses quickly?

Can users lodge support tickets?

Are these tickets viewable to everyone?

Can users that are having the same problem vote on these tickets so you can quickly identify high priority issues (and then add the resolutions to your FAQ)?

Are these tickets only for problems or are they for suggestions to improve your programs?

Are these tickets tracked? Will you automatically email users so that they are kept updated on the progress of the ticket? Users don't want to come back to your site over and over only to find that nothing has changed.


答:
I'm with you; I do it the second way.  To me, it's logically clearer.  The concern that some languages will execute the second part even if the first evaluates to false seems a tad silly to me, as I have never in my life written a program that ran in "some languages"; my code always seems to exist in a specific language, which either can handle that construction or can't.  (And if I'm not sure whether the specific language can handle it, that's something I really need to learn, isn't it.)

In my mind, the hazard with the first way of doing it is that it leaves me vulnerable to accidentally putting in code outside of that nested if block when I didn't mean to.  Which, admittedly, is hardly a huge concern, but it seems more reasonable than fretting over whether my code is language agnostic.


问:
Stack-instructions machines
When I look up "stack machine" I often get stuff like the JVM that uses a stack for data, but it still uses an array to store its instructions.

I would like to find out more about machines whose programs are stacks. For example, executing the command at the top of the stack by default removes the element at the top of the stack, and the program execution ends when the instruction stack is empty.

I'm afraid that this might be a silly question, but I have no idea what else these may be called.

I would like to know what the implementation of such a machine would look like (for example, how control flow might be handled on such a machine, how expressive the instruction set might be, etc.). A link to a Wikipedia page or some other reference would be really cool too.

While Forth, JVM bytecode, and others are heavily "stack-based", their program memory is not because the executable is always "there" like in a constant array, and if you want to branch to a different location you simply adjust the program counter.

On the other hand, in the hypothetical machine with a stack-instruction set you always execute the next instruction on the top of the stack. As Winston suggests, conditionals could be implemented by pushing various instructions onto the instruction stack.

For instance, you could have a PRINTFOR instruction that takes the number from the top of the data stack and puts that many PRINT instructions at the top of the execution stack.

For instance, if your original program was (in Forth style):

```<code>1 3 2 PRINTFOR
</code>```

At some point you will have:

Program Stack: PRINTFOR

Data Stack:    2 3 1

Then you will have:

Program Stack: PRINT PRINT

Data Stack:    3 1

And you will see

```<code>3
1
</code>```

on stdout.

I was curious as to what a "fully featured language" that takes on this kind of approach might look like.

@Mark Booth, I might just be asking an impractical question, and I might only have thought of this because of my inexperience. I'll try to explain why I wanted such an architecture.

I had worked through the Lex and Yacc tutorial Lex & Yacc Tutorial by Tom Niemann.

When I got to the part where he implements the calculator on a hypothetical stack-based machine, I spent some time implementing a VM myself.

However, I felt that at a couple of points the design could be easier for me to implement. In order to manage control flow, the machine uses some form of goto, and label. However, this would mean that in order to run an instruction, my machine would have to be aware of all the goto's all over the place. In some sense each instruction wouldn't be "context-free", and I was afraid this was bound to be more work than the alternative.

Instead of using a label, I could have goto take an instruction location (or an offset) so that I could simply set the pc to goto's operand. But this still seemed kind of messy to me. It still felt like the goto had to "know" stuff about the other instructions (and where they were) and the implementation could be cleaner.

I thought putting the operands on a stack was really cool, because it took away a lot of choices I didn't really care about when I dealt with registers. I figured maybe somebody has done something similar for instruction memory.

The benefit of such a system might be that each instruction is in some sense, "context-free", that is, when I implement the individual instructions, I don't have to worry about how many instructions there are, all I have to worry about are what the previous instructions have done (that is, the result of the data stack(s)), and what the instructions in the future are going to do (that is, the stuff left on the instruction stack). An interesting consequence would be that even in the middle of a while loop, all instructions you are going to perform in the future is considered an instruction "down the stack".
i.e.

If I have:

```<code>int x = 0;
while (True) {
  x++;
  if (x > 100) break;
  print(x);
}
</code>```

The "print" statement is physically placed below the "x++" statement, and it gets executed after the "x++" statement. However, when we reach the "print" statement, it can't forget about all the instruction that came before it. We still have to remember that the while loop closes the ending brace.

Furthermore, we don't know exactly which of the previous statements we are going to execute. In a stack-based instruction set, we can forget any instruction that has come before, and simply claim "We're going to do everything that's left in the instruction stack." This way it also becomes easier to see a program as the composition of other programs.

I'm afraid that some experienced coders might find that this really silly, because the design might end up imposing severe limitations that can only be overcome by doing things the old way, or I'm just making the classic way of implementing a VM harder than it is. However if this is the case, it would be cool if you could leave some comments to help me understand. On the other hand, I'm having trouble on how the idea might blow into a full instruction set, so even if it were possible, I'm not sure how it might be done.

答:
The closest is probably Malbolge.

Malbolge is a public domain esoteric programming language invented by
Ben Olmstead in 1998, named after the eighth circle of hell in Dante's
Inferno, the Malebolge.

The peculiarity of Malbolge is that it was
designed to be the most difficult and esoteric programming language.
However, several of the tricks used to make understanding it difficult
can be simplified away.

Title: Stack-instructions machines


答:
You shouldn't need the entire stack for each developer.  Having a Jenkins server locally would be overkill and isn't necessary.

Better instead to have one system as a build server, which runs a commonly used build script, and to take care of all the messy deployment stuff that you don't want happening ad-hoc at each workstation.

Each programmer has their development environment, the full suite of testing tools and APIs required, and can run the common build script locally.  Doing this allows all of the builds to work in the same way, and to allow through the process of continuous integration to determine if their changes are likely to break the build.  We have a commitment where I work of making sure that when our code is moved to the version control system, that it should not break the build, so building locally allows us to catch any silly problems that could leave the build in a seemingly permanent broken state.

Once we've checked our code in, the build system confirms that the source code has change, and it automatically launches a build process.  If the build works on my PC, but breaks on the build system, then it is usually because either I forgot to check something in, or because another developer has changed something in the meantime that might have affected the way my code executes... although this usually happens to be because I would have forgotten to refresh my code base prior to my build, which (yes I know) should probably happen automatically at the start of my local build script execution.


问:
How to quickly try out Java code?
When I'm coding in Python and I want to try something out, I open IDLE of Python on the command line and am able to quickly try something out. Is there a similar way I could do that for Java?

I have heard about Java "shells" (e.g. http://www.beanshell.org/). Has anyone tried them?

答:
Groovy is perhaps better suited to your needs. As wikipedia notes, "Most Java code is also syntactically valid Groovy."

Here's an example of a Groovy web console

Title: How to quickly try out Java code?


答:
I'd use ideone. Offers many languages, including Java.

ideone is something more than a pastebin; it's an online compiler and debugging tool which allows to compile and run code online in more than 40 programming languages...

Choose a programming language, enter your source code and input data into text boxes. Then check or uncheck run code (whether to execute your program) and private (whether not to list your code in the recent codes page) checkboxes, click the submit button and watch your snippet being executed...

Title: How to quickly try out Java code?

Body:
When I'm coding in Python and I want to try something out, I open IDLE of Python on the command line and am able to quickly try something out. Is there a similar way I could do that for Java?

I have heard about Java "shells" (e.g. http://www.beanshell.org/). Has anyone tried them?


答:
The most prominent ones I can think of are Forth, PostScript (seriously) and Factor.

If you want to try them out

Factor is implemented on the big 3 OSes,

GForth is available for Linux, Cygwin and I think there's a build for OS X somewhere, but the language is mostly used for embedded programming. Also, here's a (surprisingly short) tutorial that takes the form of implementing an HTTP server in Forth.

PostScript is available pretty damn much everywhere (even if you can't find an interpreter on your machine, chances are your printer speaks it). References(pdf warning) are available.

Title: Stack-instructions machines

Body:
When I look up "stack machine" I often get stuff like the JVM that uses a stack for data, but it still uses an array to store its instructions.

I would like to find out more about machines whose programs are stacks. For example, executing the command at the top of the stack by default removes the element at the top of the stack, and the program execution ends when the instruction stack is empty.

I'm afraid that this might be a silly question, but I have no idea what else these may be called.

I would like to know what the implementation of such a machine would look like (for example, how control flow might be handled on such a machine, how expressive the instruction set might be, etc.). A link to a Wikipedia page or some other reference would be really cool too.

While Forth, JVM bytecode, and others are heavily "stack-based", their program memory is not because the executable is always "there" like in a constant array, and if you want to branch to a different location you simply adjust the program counter.

On the other hand, in the hypothetical machine with a stack-instruction set you always execute the next instruction on the top of the stack. As Winston suggests, conditionals could be implemented by pushing various instructions onto the instruction stack.

For instance, you could have a PRINTFOR instruction that takes the number from the top of the data stack and puts that many PRINT instructions at the top of the execution stack.

For instance, if your original program was (in Forth style):

```<code>1 3 2 PRINTFOR
</code>```

At some point you will have:

Program Stack: PRINTFOR

Data Stack:    2 3 1

Then you will have:

Program Stack: PRINT PRINT

Data Stack:    3 1

And you will see

```<code>3
1
</code>```

on stdout.

I was curious as to what a "fully featured language" that takes on this kind of approach might look like.

@Mark Booth, I might just be asking an impractical question, and I might only have thought of this because of my inexperience. I'll try to explain why I wanted such an architecture.

I had worked through the Lex and Yacc tutorial Lex & Yacc Tutorial by Tom Niemann.

When I got to the part where he implements the calculator on a hypothetical stack-based machine, I spent some time implementing a VM myself.

However, I felt that at a couple of points the design could be easier for me to implement. In order to manage control flow, the machine uses some form of goto, and label. However, this would mean that in order to run an instruction, my machine would have to be aware of all the goto's all over the place. In some sense each instruction wouldn't be "context-free", and I was afraid this was bound to be more work than the alternative.

Instead of using a label, I could have goto take an instruction location (or an offset) so that I could simply set the pc to goto's operand. But this still seemed kind of messy to me. It still felt like the goto had to "know" stuff about the other instructions (and where they were) and the implementation could be cleaner.

I thought putting the operands on a stack was really cool, because it took away a lot of choices I didn't really care about when I dealt with registers. I figured maybe somebody has done something similar for instruction memory.

The benefit of such a system might be that each instruction is in some sense, "context-free", that is, when I implement the individual instructions, I don't have to worry about how many instructions there are, all I have to worry about are what the previous instructions have done (that is, the result of the data stack(s)), and what the instructions in the future are going to do (that is, the stuff left on the instruction stack). An interesting consequence would be that even in the middle of a while loop, all instructions you are going to perform in the future is considered an instruction "down the stack".
i.e.

If I have:

```<code>int x = 0;
while (True) {
  x++;
  if (x > 100) break;
  print(x);
}
</code>```

The "print" statement is physically placed below the "x++" statement, and it gets executed after the "x++" statement. However, when we reach the "print" statement, it can't forget about all the instruction that came before it. We still have to remember that the while loop closes the ending brace.

Furthermore, we don't know exactly which of the previous statements we are going to execute. In a stack-based instruction set, we can forget any instruction that has come before, and simply claim "We're going to do everything that's left in the instruction stack." This way it also becomes easier to see a program as the composition of other programs.

I'm afraid that some experienced coders might find that this really silly, because the design might end up imposing severe limitations that can only be overcome by doing things the old way, or I'm just making the classic way of implementing a VM harder than it is. However if this is the case, it would be cool if you could leave some comments to help me understand. On the other hand, I'm having trouble on how the idea might blow into a full instruction set, so even if it were possible, I'm not sure how it might be done.


问:
Is it necessary to read every single byte to check if a copied file is identical to the original?
I recently learned of a program called Total Commander. It's a Windows Explorer replacement and has its own stuff to copy files. To check whether the files are identical, instead of calculation a CRC, it literally checks every single byte, one at a time, on both the original and the copy.

My question is: Is this necessary? Can CRC or any other such technique go wrong? Should you, as a programmer, try and implement this perfect but slow system, or is it too extreme?

答:
As others have said it's faster to do a byte-by-byte comparison if the two files are on the same system.  If you're trying to compare a bunch of files you'll reach the point where hashing is the better answer if the files are on spinning storage.

Hashing really shines when do you don't have all the data readily available.  For example, the files are on different machines.  It also lets you save the results of calculations and refer to them later.  (Is this report the same as the old one?  When you make the report save a hash of it.  When you make the next one you can simply compare the hashes.  Not only do you not need to read the old one in you don't even need to have a copy of it available.)


答:
Well, I suppose you could make the program a stack.

Calling a function would push the code for that function onto the stack.

Conditionals could be implemented by selecting from two different lists to push onto the stack.

With conditions + recursion you've got everything you need in terms of logic flow.

I don't know anybody that has done this, and I don't know you would do it, but I guess you could.

Title: Stack-instructions machines


答:
I seem to remember the ZPU is a stack based processor. It has an open source core, GCC toolchain, etc.

Have a look and see if it is what you are talking about or if it is array-based.

Title: Stack-instructions machines


答:
If you have Eclipse open and a program in debug I like to use the Display window to quickly test out Java code snippets real time.  If I am not debugging something I generally just code snippets into a JUnit test case and run them to see what happens.

I know it is not the best way but it is often good enough for my needs.

Title: How to quickly try out Java code?


答: If you download the free BlueJ IDE you can use the code pad area to try out snippets of code on the fly.

Title: How to quickly try out Java code?


问:
Are super methods in JavaScript limited to functional inheritance, as per Crockford's book?
In Douglas Crockford's "JavaScript: The Good Parts", he walks through three types of inheritance: classical, prototypal, and functional. In the part on functional inheritance he writes:

"The functional pattern also gives us a way to deal with super methods."

He then goes on to implement a method named "superior" on all Objects. However, in the way he uses the superior method, it just looks like he is copying the method on the super object for later use:

```<code>// crockford's code:
var coolcat = function(spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};
</code>```

The original get_name method is copied to super_get_name. I don't get what's so special about functional inheritance that makes this possible. Can't you do this with classical or prototypal inheritance? What's the difference between the code above and the code below:

```<code>var CoolCat = function(name) {
    this.name = name;
}

CoolCat.prototype = new Cat();

CoolCat.prototype.super_get_name = CoolCat.prototype.get_name;
CoolCat.prototype.get_name = function (n) {
    return 'like ' + this.super_get_name() + ' baby';
};
</code>```

Doesn't this second example provide access to "super methods" too?

答: The answer is public versus private. With the functional approach, super methods can be kept private to the object. The second example (using prototype) exposes the super method publicly.</p>


问:
When to Use workflow engines?
I've worked in past on some of the workflow engines as programmer but never had a clarity on why we chose the work-flow engines in first place. And as programmer I know that there are at least 100 ways to do anything when you are writing code but only few of the ways are the best!

I still don't understand which use cases are best solved by workflow engines (or rather their concept) than designing a good DI enabled application. I'm looking for any general characteristics of domain-neutral use cases, where work-flow engines are one of the the best options.

So my question is: What are general characteristics of a requirement which can be taken as a signal for opting for a good workflow engine and coding around it?

答:
This looks like an old question, but surfaces numerous times in the wild. I agree with Jon's answer. I have found workflow engines to be highly productive in the following scenarios:

There is an underlying business process that you are trying to represent / implement through your software.

There is a single (maybe composite) business entity that is worked upon in all or some of the stages in the process. In the example Jon gave, this entity or Workflow Item would be content, or an article. Consider bug tracking as another example of a workflow, a Bug transitions between various states, based on an action a user takes.

Use Workflows to model your processes, only if you expect the business process to change, by change I mean the sequence or action performed as a result of a user action or transition.

Be very careful and critical to see if your problem domain / requirements has a business process, don't try to "fit" it into a workflow.

Title: When to Use workflow engines?


答:
If you work in Delphi, the first way is, in general, safer. (For the given example, there's not much to gain from using nested ifs.)

Delphi allows you to specify whether or not boolean expressions evaluate or "short circuit", through compiler switches. Doing way #1 (nested ifs) allows you to ensure that the second clause executes if and only if (and strictly after) the first clause evaluates to true.


问:
Load testing : how to generate per second requests?
I have a server component which runs over Zeroc-ICE. When I wanted to load test it, I thought that using parallel library to create multiple requests would do it. But it dint end up that way. Using Parallel(Parallel.For) library from C# apparently was easier but it doesn't seem to be exactly generating everything parallel in the same instant. So it cannot be the definition for creating N requests per second. How should I do it ? I guess anyone who wants to do load testing first would actually think about this .

What's the efficient way to actually create N requests in really per second ?

Another myth is about the parallel programming. Please enlighten us , if you have used parallel programming patterns in C# or .Net in general . Imagine I have 5 processes. How will start all the five processes at the same time. What does it mean to my consumption of resources ? I have tried reading into many of the material available over the net but I get more and more questions than them being the answer to my questions.

I used Parallel.For and created N threads and measured time. Then I tried the same thing using Task.Factory.start for enumeration of tasks. The time measured was different. So What exactly is the different between using these ? When I should use the corresponding classes and for what purposes exactly ? we often have lots of riches but its just we exactly don't know how to differentiate one from the another. This is one such case for me, not being able to find why I should not use one from the another.

I used the stopwatch class to measure these times which claims to be the best. In the scenario of me load testing a component, what would be the way to measure the time of response. Stopwatch seems to be the best solution for me . Any opinions are welcome.

ps: There are many load testing tools for web applications. Mine is a customised case of server components. And my question is more pertaining to creating N threads per second.

All opinions are welcome. Just don't think its so much not a programming question. It ofcourse is. It should ring bells for any programmer who wants to QE stuff by himself to know the performance of his product , first hand by himself.I have tried many options and then had to fall back on how should I actually do it ?

答:
I'm going to skip over question 1) and get right into #2, since that's generally an acceptable way to accomplish what you're looking for. In the past to achieve n messages per second you can create a single process that will then launch p AppDomains. Each AppDomain basically just starts running a request loop once a certain point in time has been reached (using a Timer). This time should be same for each AppDomain to ensure that they start hitting your server at the same point in time.

Something like this should work for sending your requests:

```<code>WaitCallback del = state =>
{
    ManualResetEvent[] resetEvents = new ManualResetEvent[10000];
    WebClient[] clients = new WebClient[10000];

    for (int index = 0; index < 10000; index++)
    {
        resetEvents[index] = new ManualResetEvent(false);
        clients[index] = new WebClient();

        clients[index].OpenReadCompleted += new OpenReadCompletedEventHandler (client_OpenReadCompleted);

        clients[index].OpenReadAsync(new Uri(@"<REQUESTURL>"), resetEvents[index]);
    }

    bool succeeded = ManualResetEvent.WaitAll(resetEvents, 10000);
    Complete(succeeded);

    for (int index = 0; index < 10000; index++)
    {
        resetEvents[index].Dispose();
        clients[index].Dispose();
    }
};

while(running)
{
    ThreadPool.QueueUserWorkItem(del);
    Thread.Sleep(1000);
}
</code>```

This will probably crush performance on whichever machine you're running it on, so you could always implement a simmilar type of loop from several different machines if you have the resources (using processes instead of app domains).

For your third question, give this link a read http://www.albahari.com/threading/

Finally, a stopwatch should be paired with a hit counter to track both duration & unique hits on your server. That should let you perform some analysis after the fact.

OwnerDisplayName: King

Body:
I'm going to skip over question 1) and get right into #2, since that's generally an acceptable way to accomplish what you're looking for. In the past to achieve n messages per second you can create a single process that will then launch p AppDomains. Each AppDomain basically just starts running a request loop once a certain point in time has been reached (using a Timer). This time should be same for each AppDomain to ensure that they start hitting your server at the same point in time.

Something like this should work for sending your requests:

WaitCallback del = state =>
{
    ManualResetEvent[] resetEvents = new ManualResetEvent[10000];
    WebClient[] clients = new WebClient[10000];

    for (int index = 0; index < 10000; index++)
    {
        resetEvents[index] = new ManualResetEvent(false);
        clients[index] = new WebClient();

        clients[index].OpenReadCompleted += new OpenReadCompletedEventHandler (client_OpenReadCompleted);

        clients[index].OpenReadAsync(new Uri(@"<REQUESTURL>"), resetEvents[index]);
    }

    bool succeeded = ManualResetEvent.WaitAll(resetEvents, 10000);
    Complete(succeeded);

    for (int index = 0; index < 10000; index++)
    {
        resetEvents[index].Dispose();
        clients[index].Dispose();
    }
};

while(running)
{
    ThreadPool.QueueUserWorkItem(del);
    Thread.Sleep(1000);
}

This will probably crush performance on whichever machine you're running it on, so you could always implement a simmilar type of loop from several different machines if you have the resources (using processes instead of app domains).

For your third question, give this link a read http://www.albahari.com/threading/

Finally, a stopwatch should be paired with a hit counter to track both duration & unique hits on your server. That should let you perform some analysis after the fact.