问:
Concurrent Data Processing by Multiple People
Let's say I have a page, accessible by several people concurrently, that lists information that must be processed in some way by the user, after which it is either marked as "completed" and effectively disappears, or is left unprocessed and thus left in the list to be tried again later. What is the best way to ensure that only one person is handling a given item in the list at a time, assuming that I must show the list (i.e. no one user/one item requirement, which is what I would prefer), and that any given user can click on any item in the list at any time?

This is an issue that has come up several times where I work, and I'm not really satisfied with the solution that I've implemented up until now. I was hoping someone had a better idea.

Basically my solution involved creating a table in a database to track who accessed what item and when, and then enabling/disabling features based on that (e.g. not allowing a user to edit info if it's checked out by someone else). It looks something like the following (using Oracle 11g...these are stripped way down for brevity here, with INFO columns acting as a stand in for all other columns that are irrelevant here).

```CREATE TABLE "SOME_INFO"
(
  "INFO_ID"       NUMBER(19,0)      NOT NULL ENABLE,
  "INFO"          VARCHAR2(20 BYTE) NOT NULL ENABLE,
  "IS_PROCESSED"  CHAR(1)           NOT NULL ENABLE,
  CHECK ("IS_PROCESSED" IN ('Y', 'N')) ENABLE,
  CONSTRAINT "PK_SOME_INFO" PRIMARY KEY ("INFO_ID") USING INDEX
); /

CREATE TABLE "SOME_PERSON"
(
  "PERSON_ID" NUMBER(19,0)      NOT NULL ENABLE,
  "INFO"      VARCHAR2(20 BYTE) NOT NULL ENABLE,
  CONSTRAINT "PK_SOME_PERSON" PRIMARY KEY ("PERSON_ID") USING INDEX
); /

CREATE TABLE "PROCESS_HISTORY"
(
  "INFO_ID"       NUMBER(19,0)  NOT NULL ENABLE,
  "PROCESSOR_ID"  NUMBER(19,0)  NOT NULL ENABLE,
  "CHECKED_OUT"   DATE          NOT NULL ENABLE,
  "CHECKED_IN"    DATE
); /```

"Checking out" a record from SOME_INFO for a given user is accomplished by INSERTing a new record into PROCESS_HISTORY with INFO_ID = the selected record's INFO_ID, PROCESSOR_ID = the users PERSON_ID, and CHECKED_OUT = the current time (CHECKED_IN is left NULL).

"Checking In" is accomplished by simply setting CHECKED_IN to the current time. An automated process is used to periodically check in records that have been checked out for more than some predefined maximum amount of time (the time varies from page to page based on what's involved in processing the info).

From this I can tell if a given record is currently checked out or not, and thus alter the page's behavior accordingly. Having said that, I can't help but think there's got to be a better way to do this. I'm hoping it's a common enough problem that there is a standard or semi-standard method of doing this that I simply haven't been able to find.

答:
You have a typical case of resource-sharing problem. You should read about http://en.wikipedia.org/wiki/Semaphore_(programming)
http://en.wikipedia.org/wiki/Monitor_(synchronization)

Probably you should use a transaction approach, not allowing different users work on the same data at the same time, but reading those two will clear your mind about the problems you are facing.


答:
I'm hoping it's a common enough problem

Yes and no.

It's common.

But.

In many cases, a check-in/check-out feature usually indicates a design problem somewhere else.

Let's say I have [data], accessible by several people concurrently, that lists information that must be processed in some way by the user, after which it is either marked as "completed" and effectively disappears, or is left unprocessed and thus left in the list to be tried again later.

This is a very, very typical "work queue" situation.  Often, you can save yourself mountains of grief by "assigning" the work to the individual "sub-queues" so that a person only sees work assigned to them.  There's no complex "check-out/check-in"; instead the work is allocated to "sub-queues".

There's no check-out, because there's no possibility for one person to see work outside their sub-queue.  The contents of their queue may change, as things are removed from someone else's queue and assigned to theirs.

If they decline to work on something, it may get assigned to another work queue.    If something has waited too long it can go to a high-priority queue.  You can have tiers of people working on slightly different things.  Splitting up the work queue usually allows a lot of expansion, tuning and adjustment.

there is a standard or semi-standard method of doing this that I simply haven't been able to find.

Not really.  "Standard" doesn't apply, since each situation is unique.

ContentLicense: CC BY-SA 3.0

Title: Concurrent Data Processing by Multiple People

Body:
Let's say I have a page, accessible by several people concurrently, that lists information that must be processed in some way by the user, after which it is either marked as "completed" and effectively disappears, or is left unprocessed and thus left in the list to be tried again later. What is the best way to ensure that only one person is handling a given item in the list at a time, assuming that I must show the list (i.e. no one user/one item requirement, which is what I would prefer), and that any given user can click on any item in the list at any time?

This is an issue that has come up several times where I work, and I'm not really satisfied with the solution that I've implemented up until now. I was hoping someone had a better idea.

Basically my solution involved creating a table in a database to track who accessed what item and when, and then enabling/disabling features based on that (e.g. not allowing a user to edit info if it's checked out by someone else). It looks something like the following (using Oracle 11g...these are stripped way down for brevity here, with INFO columns acting as a stand in for all other columns that are irrelevant here).

```CREATE TABLE "SOME_INFO"
(
  "INFO_ID"       NUMBER(19,0)      NOT NULL ENABLE,
  "INFO"          VARCHAR2(20 BYTE) NOT NULL ENABLE,
  "IS_PROCESSED"  CHAR(1)           NOT NULL ENABLE,
  CHECK ("IS_PROCESSED" IN ('Y', 'N')) ENABLE,
  CONSTRAINT "PK_SOME_INFO" PRIMARY KEY ("INFO_ID") USING INDEX
); /

CREATE TABLE "SOME_PERSON"
(
  "PERSON_ID" NUMBER(19,0)      NOT NULL ENABLE,
  "INFO"      VARCHAR2(20 BYTE) NOT NULL ENABLE,
  CONSTRAINT "PK_SOME_PERSON" PRIMARY KEY ("PERSON_ID") USING INDEX
); /

CREATE TABLE "PROCESS_HISTORY"
(
  "INFO_ID"       NUMBER(19,0)  NOT NULL ENABLE,
  "PROCESSOR_ID"  NUMBER(19,0)  NOT NULL ENABLE,
  "CHECKED_OUT"   DATE          NOT NULL ENABLE,
  "CHECKED_IN"    DATE
); /```

"Checking out" a record from SOME_INFO for a given user is accomplished by INSERTing a new record into PROCESS_HISTORY with INFO_ID = the selected record's INFO_ID, PROCESSOR_ID = the users PERSON_ID, and CHECKED_OUT = the current time (CHECKED_IN is left NULL).

"Checking In" is accomplished by simply setting CHECKED_IN to the current time. An automated process is used to periodically check in records that have been checked out for more than some predefined maximum amount of time (the time varies from page to page based on what's involved in processing the info).

From this I can tell if a given record is currently checked out or not, and thus alter the page's behavior accordingly. Having said that, I can't help but think there's got to be a better way to do this. I'm hoping it's a common enough problem that there is a standard or semi-standard method of doing this that I simply haven't been able to find.


问:
Looking for a distributed locking pattern
I need to come up with a custom recursive object locking mechanism\pattern for a distributed system in C#. Essentially, I have a multi-node system. Each node has exclusive write permissions over n-number pieces of state. The same state is also  available in read-only form on at least one other node. Some writes/updates must be atomic across all nodes, while other updates will eventually become consistent thru background replication processes, queues, etc...

For the atomic updates I'm looking for a pattern or samples that efficiently allow me to mark an object as locked for writes which I can then distribute, commit, rollback, etc... Since the system has high-levels of concurrency, I'm assuming I'll need to be able to stack-up locks which will either timeout or be unrolled once the locks are released.

The transaction or messaging pieces are not the focus of this question, but I've provided them for some extra context. With that said, feel free to articulate what messages you think would be needed if you like.

Here is a vague sample of what I was envisioning although I'm open to any new ideas aside from implementing whole new products

```<code>thing.AquireLock(LockLevel.Write);

//Do work

thing.ReleaseLock();
</code>```

I was thinking of using extension methods, which might look something like this

```<code>public static void AquireLock(this IThing instance, TupleLockLevel lockLevel)
{
    //TODO: Add aquisition wait, retry, recursion count, timeout support, etc...
    //TODO: Disallow read lock requests if the 'thing' is already write locked
    //TODO: Throw exception when aquisition fails
    instance.Lock = lockLevel;
}

public static void ReleaseLock(this IThing instance)
{
    instance.Lock = TupleLockLevel.None;
}
</code>```

To clarify a couple details...

All communications are TCP/IP using a binary request/response protocol

There are no intermediary technologies such as queues or databases

There is no central master node. In this case, the locking arrangement is defined by the initiator of the lock and the partner which will honour the request with some form of timeout to govern its behaviour

Anyone have any suggestions?

答:
Thanks for the clarifications.

In that case, what I'd recommend is using a publish / subscribe model.  Google's Chubby distributed locking protocol ( an implementation of Paxos)

I've never used Paxos (or Chubby), but there seems to be an open source implementation here.

If that doesn't work, you could implement your own version of Paxos using, for example, one of the usual suspects in terms of messaging libraries : the zero message queue library,  RabbitMQ, or ActiveMQ.

Previous Answer:

Most of the suggestions on SO ([A], [B]) go for use of a message queue to achieve cross-machine locking.

Your AcquireLock method would push something identifying the lock object into the queue, checking for previous instances of locks before success.  Your ReleaseLock method would remove the lock object from the queue.

SO user atlantis suggests, in this post, Jeff Key's post for some of the detail.


问:
At the end of my rope
I am a contractor to a big company.  Currently, there are three developers on the project, myself included.

The problem is the other 2 developers don't really get it.  By "it" i mean the following:

They don't understand the best practices for the technology we are using.  After 6 months of me and others giving them examples there are terrible anti-patterns being used.

They are "copy and paste" programmers that produce primarily spaghetti code.

They constantly break things, implementing changes but not doing a basic smoke test
to see if all is good

They refuse/rarely to ask for code-reviews.

They refuse/rarely even do basic things like formatting code.

No documentation on any classes (jsdocs)

Afraid to delete code that doesn't do anything

Leave commented code blocks everywhere even though we have version control.

I find myself getting more and more frustrated as I format others code, fix bugs, discover functionality that is broken, and create abstractions to remove the spaghetti.

I really don't know what to do.  I try not to get to frustrated, but it's just a mess.  I like these people as people, but I feel like the coding situation is so bad that I could move faster if they simply browsed the web all day.

Would it be out of line to ask our manager to review the others svn commit access; commits can only be done after a review by someone who is knowledgeable in what we are doing?  As a contractor, I'm not sure if that's the best move.

Is there a subtle/not so subtle way of making it clear how many things I am fixing?

答:
I suggest that you speak to your manager about the issue, but he is almost certainly not going to want to review every single check-in.

Instead I suggest that you suggest a suite of unit/regression tests, to be hooked into SVN, and run for every checkin. That will at least help you avoid broken builds. You can gradually suggest other best practices.

If he turns out to be entirely unreceptive, maybe you should go over his head. If you do decide to do that, you will need to bring your best game. You will basically be pitching to management to be hired at a higher level if you do that.

Title: At the end of my rope


答:
I'm having something like this on my team. I tried hard to get people to do the right thing and it didn't work as expected so I moved to a different solution.

First, I went to my manager and we worked out a deal, no code whatsoever gets into the source control unless it's covered by unit tests. If code gets in without unit tests I have veto power to undo the commit right away and ping whoever was responsible to they can work on tests and then push the code.

With this rule in place, I regularly run code coverage tools (in this case, jacoco in our sbt build) to make sure pieces are correctly covered and I'm also doing refactorings and code reviews constantly in any code pushed by them. As this is a Java and Scala project I have plenty of tools to help me catch stuff that should not be there or that doesn't work the way we think it should, not sure how you can do the same with JavaScript but maybe there is a solution.

The main thing I believe is helping me on keeping up with this is that I do have a clear view of what I expect of the project and it's main architecture, so whenever I see something that does not reflect this view, i can go there and fix it. You should do the same, define your view, the patterns that should be used, the way code should be written and keep yourself on top of this, always letting them (and your management) know what's happening and what's keeping the project from moving on faster.

There will surely be a moment where either they give up and do the right thing or the management gets the message and removes them from the project.

Title: At the end of my rope

Body:
I am a contractor to a big company.  Currently, there are three developers on the project, myself included.

The problem is the other 2 developers don't really get it.  By "it" i mean the following:

They don't understand the best practices for the technology we are using.  After 6 months of me and others giving them examples there are terrible anti-patterns being used.

They are "copy and paste" programmers that produce primarily spaghetti code.

They constantly break things, implementing changes but not doing a basic smoke test
to see if all is good

They refuse/rarely to ask for code-reviews.

They refuse/rarely even do basic things like formatting code.

No documentation on any classes (jsdocs)

Afraid to delete code that doesn't do anything

Leave commented code blocks everywhere even though we have version control.

I find myself getting more and more frustrated as I format others code, fix bugs, discover functionality that is broken, and create abstractions to remove the spaghetti.

I really don't know what to do.  I try not to get to frustrated, but it's just a mess.  I like these people as people, but I feel like the coding situation is so bad that I could move faster if they simply browsed the web all day.

Would it be out of line to ask our manager to review the others svn commit access; commits can only be done after a review by someone who is knowledgeable in what we are doing?  As a contractor, I'm not sure if that's the best move.

Is there a subtle/not so subtle way of making it clear how many things I am fixing?


问:
Why is #include <iostream.h> bad?
I was reading another thread where a guy asked about C++ books for beginners, and one of the programmers answering wrote this:

Some warnings: avoid all books that present an "hello world" stating with

```<code>#include <iostream.h>
</code>```

I opened my C++ book and sure enough it included the iostream header like the example above.

Why is that bad? What other pointers should I keep in mind when learning C++?

Background: I am proficient with C and I'll start to learn C++ this next semester.

答:
#include <iostream.h> is a sign that the book was written prior to the first C++ standard in 1998 (the standard header is iostream).

The problem is that older C++ code tends to be written in ways that are considered bad practice today.  In particular,

The use of C-style arrays rather than container classes like std::string and std::vector.

The use of explicit close functions rather than RAII.

iostream.h isn't the worst thing a pre-1998 book will get wrong, but it's likely to be the first thing that a pre-1998 book will get wrong.

Title: Why is #include <iostream.h> bad?


问:
Is there an IDE for python that creates the same kind of reflective environment that Smalltalk provides?
As anyone who has used Smalltalk knows, one of the main benefits (other than a late-bound language that discourages many poor practices), is that the system is totally transparent and reflective, which makes understanding APIs and existing code easy, and locating functionality pretty easy.

Is there anything that creates a similar environment for Python?

A few examples of features of a smalltalk development environment, not natively found in python are:

search class/method/etc names,

examine inheritance hierarchies

functionality to show the full interface of a given class/object, and where the properties therein originate

an integrated graphical debugger which allows one to examine the full state of everything in the system, and see every instance of a given type, as well as all threads.

Note that I use windows, so anything that works well on windows would be particularly useful.

答:
ipython adds lots of syntactic sugar over the default Python REPL. In particualr, you get tab-completion, a nice "?" shortcut for the help() function and everything is nicely colorized and easier to read.

Not quite a Smalltalk environment but I find it very helpful.


问:
Right license(s) for a freemium offer
I am currently working on a solution written in JavaScript. I plan to release two versions:

For free: the lite one with base options, which is plug and play (it just works when loaded in the page)

For a subscription fee: the full version that has more options and requires support

I am wondering which license(s) would work for me. Here are my thoughts so far, feel free to correct me:

MIT: I am concerned that somebody else might release new features on top of my solution, under a commercial license. It means that I wouldn't be able to add these same features to my own solution in the future.

GPL: doesn't seem to work in my case, if I release the lite version under GPL then it means that I also need to release the full version for free.

Dual licensing: I see that some frameworks or libraries offer dual licensing, but I am not sure how it works.

答:
You are perfectly free to license the software under GPL, and under a commercial license. The GPL's copyleft requirements do not apply to the copyright owner, only to people who need the GPL to be allowed to copy and modify the software.

That's how dual licensing works.

Of course, for details you'd need to ask a lawyer, but the Wikipedia page is a decent introduction: http://en.wikipedia.org/wiki/Dual_licensing

Edit:

To clarify my statement that "the GPL's copyleft requirements do not apply to the copyright owner": This is just basic copyright law. Under copyright law (and related law), the copyright owner has all rights. Releasing code under any license (such as the GPL) just grants some of these rights to others, along with any restrictions the copyright holder wants to attach.

The restrictions imposed by the GPL are only binding because without a license you would not be allowed to copy and modify the software at all - because of copyright law. This is the idea behind "copyleft". All this, of course, does not apply to the copyright holder.

Straight from the GPL FAQ from the FSF:

Q: I would like to release a program I wrote under the GNU GPL,
  but I would like to use the same code in non-free programs.

A: To release a non-free program is always ethically tainted, but
  legally there is no obstacle to your doing this. If you are the
  copyright holder for the code, you can release it under various
  different non-exclusive licenses at various times.

Source: http://www.gnu.org/licenses/gpl-faq.html#ReleaseUnderGPLAndNF

Edit 2:

One more clarification: The whole dual-licensing thingie only works as long as you are the copyright owner for all the code. As soon as you start accepting code from others, you will be bound by whatever license they choose for their contribution. I.e., if you accept GPL-licensed code into your codebase, any version that includes these contributions must be GPL-licensed as well.

The only way around this is for contributors to assign copyright to you - that's why many organizations require copyright assignment from contributors (e.g the FSF does this). Of course contributors might not want to assign copyright to you - in that case you'll have to convince them (e.g. by paying them), or leave their contributions out of you non-GPL version.

Title: Right license(s) for a freemium offer


问:
Can I use Ruby to automate everything?
I face various types of applications (web-based, GUI-based, command-line, etc.) on various platforms (Windows, Linux, etc.) to operate everyday. There is a great opportunity for me to automate tasks by scripting. But almost every type of application and platform has its native scripting language or tools (such as VBScript and PowerShell for Windows, Bash scripts for Linux, Selenium for web applications, and AutoIt for GUI applications, etc.). It kills me to learn and maintain so many scripting languages.

I have a feeling that Ruby can interoperate with various platforms easily, and it is very expressive. So my question is:

It is possible to use Ruby to script everything?

If it is, what are the main disadvantages compared to the native scripting language of each platform?

答:
I agree with all answers above but keep in mind that Windows and POSIX have platform specific differences so it couldn't guarantee that you can reuse your script if it uses some platform specific stuff.

Ruby is fine for general scripting but not really great for performance. Anyway it allows you to identify platform inside script and execute external commands and scripts.

Title: Can I use Ruby to automate everything?


问:
What is a practical way to debug Rails?
I get the impression that in practice, debuggers are rarely used for Rails applications. (Likewise for other Ruby apps, as well as Python.)

We can compare this to the usual practice for  Java or VisualStudio programmers--they use an interactive debugger in a graphical IDE.

How do people debug Rails applications in practice? I am aware of the variety of debuggers, so no need to mention those, but do serious Rails programmers work without them? If so, why do you choose to do it this way?

It seems to me that console printing has its limits when debugging complex logic.

答:
Yeah ruby-debug is good, also

Don't forget about IRB especially with gem's like

http://pry.github.com/

or

https://github.com/jberkel/interactive_editor

Title: What is a practical way to debug Rails?


问:
How do you know when to stop adding features?
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?

答: When you've got something reliable and useful, release.  You don't have to stop adding features, but if anybody's using what you've got out there you'll get a much better idea of what features are wanted.  Currently, you're guessing.</p>

ContentLicense: CC BY-SA 2.5


问:
Package name best practice when porting a library
What is the suggested way (specifically in the open-source world) for the package name when porting a library.

Say I am porting someone else's library where they have used a reverse domain name stucture for there package name, so there library package name was some thing like com.therename.thelib. What should I do if I decide to port it to a new language? Should I keep the domain name intact, even though they didn't have a hand in it? Or should I change it to something like com.myname.thelib?

答: I would keep it intact so that everyone can clearly see that it's semantically the same.</p>


问:
What do I need to include in my OOP design document?
I am a graduate student in aerospace engineering. A lot of my Master's thesis has been on developing an OOP software architecture in MATLAB to facilitate control of Arduino-based vehicles (blimps, cars, quadrotors, etc).

All my code is heavily documented, but my thesis itself needs to be more than a reference of every class and method - it needs to describe at a high level how each piece works together, and why my architecture is the way it is.

I only have a minor in computer engineering and I consider myself a pretty competent programmer, but I have no experience writing this kind of document. What kinds of things need to be included in the document? (Diagrams, paragraph explanations of how each class operates, etc)? I don't want to just rehash my code comments (although at the start of each file there's paragraphs of comments about how that class relates to other classes). I also wonder if it's necessary to get rather technical (I implement some fairly advanced MATLAB concepts [that is, advanced for non-computer engineers] such as listeners and callbacks); my audience also hails from an aerospace engineering background.

Examples would be appreciated if they exist.

EDIT: The part my audience really cares about is not the software architecture (the stuff this question entails); this document is really for people who will use my work in the future - who are not computer engineers! So I guess the main question is, what needs to be in the document such that people who are not up to speed on the project (and we can assume competent with the language) can understand the architecture, maintain and use the software?

答:
I currently have the same problem as you, although my software relates to business architecture (Master business engineering).

I'm planning on writing it in such a way that the high-level logic can be understood by someone with basic Object oriented knowledge. I'll be making references to the official documentation, design patters to make it easy for developers to work further on my code. Research papers will also be referenced but not in a way that you would need to read it to understand everything. The papers are just to show what I base everything on.

One tip I want to give you is to make it as visual as possible. I will for example add a scheme with my databaseHelper class at the bottom as a long bar, showing it is encapsulated by my contentprovider by drawing it above also as a bar or around it (it's an android application). This contentprovider will have links to the further abstractions that are made, other classes, ... in such a way that people will be able to understand the whole picture and make abstraction of everything else.

Just begin with the highest level of abstraction and then go down and down. In a lot of cases, if people see the big picture they will be able to make an abstraction of all underlying things and that was the purpose of your paper. You want people to be able to work with it.

So, in general:

-Visualize!
-Be technical about the stuff it's really about, the core of you masters thesis. Be clear about everything else so that people can work with it.


问:
Recommend a text that explains the physical implementation of C (stack, heap, etc)
One of the most popular questions on stackoverflow.com is this one:

https://stackoverflow.com/questions/4025768/what-do-people-find-difficult-about-c-pointers

Many of the answers seem to gravitate toward the fact that students often don't get a good understanding of what is physically going on when code executes... the very most basic part of this seems to be stack/heap.

I've read through K&R twice and finally have a good understanding of the language, but I don't think that is enough.  Nearly every tough question here has the work "stack" or "heap" in the answer, and while I have a limited understanding of what those mean just from context and wikipedia searches, I prefer the comprehensive approach of a textbook.  So, please recommend a textbook which explains things like stack, heap, memory allocation, etc from a physical standpoint, as it relates to C programming.

I tried asking this question on stackoverflow and apparently it was not the right place to ask it.  So I hope this site is a better location.  If not, please consider migrating it to the proper stackexchange site.  Thanks.

答: During my study I used the book "Programming Language Concepts" (Ghezzi, Jazayeri), which has a detailed description of execution models (global variables, stack variables, activation record, heap variables).</p>


问:
How can I design test cases to cover code based on random events?
For example, if the code generates a random int from 0-10, and takes a different branch on each outcome, how can one design a test suite to guarantee 100% statement coverage in such code?

In Java, the code might be something like:

```<code>int i = new Random().nextInt(10);
switch(i)
{
    //11 case statements
}
</code>```

答:
You can use PowerMock library to mock the Random class and stub its nextInt() method to return the expected value. No need to change your original code if you don't want to.

I'm using PowerMockito and just tested a method similar to yours. For the code that you posted the JUnit test should look something like this:

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest( { Random.class, ClassUsingRandom.class } ) // Don't forget to prepare the Random class! :)

public void ClassUsingRandomTest() {

    ClassUsingRandom cur;
    Random mockedRandom;

    @Before
    public void setUp() throws Exception {

        mockedRandom = PowerMockito.mock(Random.class);

        // Replaces the construction of the Random instance in your code with the mock.
        PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(mockedRandom);

        cur = new ClassUsingRandom();
    }

    @Test
    public void testSwitchAtZero() {

        PowerMockito.doReturn(0).when(mockedRandom).nextInt(10);

        cur.doSomething();

        // Verify behaviour at case 0
     }

    @Test
    public void testSwitchAtOne() {

        PowerMockito.doReturn(1).when(mockedRandom).nextInt(10);

        cur.doSomething();

        // Verify behaviour at case 1
     }

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

You can also stub the nextInt(int) call to receive any parameter, in case you want to add more cases at your switch:

```<code>PowerMockito.doReturn(0).when(mockedRandom).nextInt(Mockito.anyInt());
</code>```

Pretty, isn't it? :)

Body:
You can use PowerMock library to mock the Random class and stub its nextInt() method to return the expected value. No need to change your original code if you don't want to.

I'm using PowerMockito and just tested a method similar to yours. For the code that you posted the JUnit test should look something like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest( { Random.class, ClassUsingRandom.class } ) // Don't forget to prepare the Random class! :)

public void ClassUsingRandomTest() {

    ClassUsingRandom cur;
    Random mockedRandom;

    @Before
    public void setUp() throws Exception {

        mockedRandom = PowerMockito.mock(Random.class);

        // Replaces the construction of the Random instance in your code with the mock.
        PowerMockito.whenNew(Random.class).withNoArguments().thenReturn(mockedRandom);

        cur = new ClassUsingRandom();
    }

    @Test
    public void testSwitchAtZero() {

        PowerMockito.doReturn(0).when(mockedRandom).nextInt(10);

        cur.doSomething();

        // Verify behaviour at case 0
     }

    @Test
    public void testSwitchAtOne() {

        PowerMockito.doReturn(1).when(mockedRandom).nextInt(10);

        cur.doSomething();

        // Verify behaviour at case 1
     }

    (...)

You can also stub the nextInt(int) call to receive any parameter, in case you want to add more cases at your switch:

PowerMockito.doReturn(0).when(mockedRandom).nextInt(Mockito.anyInt());

Pretty, isn't it? :)


问:
Should I use the language I'm most comfortable in, or the company "standard"
I'm going to be developing an Intranet site for my specific plant, and our company standard for web-development is IIS + ASP.Net + VB.Net + Microsoft SQL Server (note that we have about 10+ plants). The Intranet site will only be used by my plant, and I'm the only one who will support it. I'm much more proficient with a LAMP setup, and I could do development and problem solving much more rapidly with PHP than I could ASP.Net. Even though the company "standard" is ASP.Net/VB.Net, most of what the company does as a whole is to purchase third party software (which is usually Java based), and very, and I do mean very few people in the company even know VB6, let alone ASP.Net/VB.Net.

That being said, is it better to violate the company standard and go with the setup that I can support better, or is it better to go with the setup that the company can support better if I ever were to leave, even though no one currently in the company can support their own standard anyway?

Some additional factors to consider in my personal case:

Again, this is only for my plant, and I'm the only one who will ever be supporting it unless I leave the company, and then my replacement would be supporting it. Not someone else already in the company.

The company does very little development with their standard anyway.

Hardly any of the companies existing software uses their standard.

If I choose the company standard, then I have to use the Express version of Microsoft SQL and a Windows 7 OS. From my readings, the Express version is okay for business use, but the database size is limited.

答:
That being said, is it better to violate the company standard and go with the setup that I can support better, or is it better to go with the setup that the company can support better if I ever were to leave, even though no one currently in the company can support their own standard anyway?

It is a management decision. Make them know your concerns and insist formally on changing.

That said, a language is a tool and you must choose the right tool for a job; make them understand that you don't screw a screw with a hammer.


答:
I think that you can anticipate many of the problems that could arise from this and make a detailed plan for if and when you ever had to leave the company.

One problem that could gum up the works would be if you left and HR had to search for your replacement.  Given they either actively try to understand what you did and hire according to the skills needed -or- simply look at the original document that spec'd out the policy of IIS/ASP.NET/etc. and blindly hire someone with those skills to maintain your LAMP code (on the "because it says so" principle), I think the latter is much more likely.

The easiest thing (in the long run) is to do what fabianhjr recommended and change the standard.  Change it to include both Microsoft and LAMP if they are resistant to a full switch.

Title: Should I use the language I'm most comfortable in, or the company "standard"

Body:
I'm going to be developing an Intranet site for my specific plant, and our company standard for web-development is IIS + ASP.Net + VB.Net + Microsoft SQL Server (note that we have about 10+ plants). The Intranet site will only be used by my plant, and I'm the only one who will support it. I'm much more proficient with a LAMP setup, and I could do development and problem solving much more rapidly with PHP than I could ASP.Net. Even though the company "standard" is ASP.Net/VB.Net, most of what the company does as a whole is to purchase third party software (which is usually Java based), and very, and I do mean very few people in the company even know VB6, let alone ASP.Net/VB.Net.

That being said, is it better to violate the company standard and go with the setup that I can support better, or is it better to go with the setup that the company can support better if I ever were to leave, even though no one currently in the company can support their own standard anyway?

Some additional factors to consider in my personal case:

Again, this is only for my plant, and I'm the only one who will ever be supporting it unless I leave the company, and then my replacement would be supporting it. Not someone else already in the company.

The company does very little development with their standard anyway.

Hardly any of the companies existing software uses their standard.

If I choose the company standard, then I have to use the Express version of Microsoft SQL and a Windows 7 OS. From my readings, the Express version is okay for business use, but the database size is limited.


答:
Seems to me like you have a couple of mixed technologies here:

communications (which you essentially rely on as being 100% reliable... which can be fatal)

locking / mutual exclusion

timeouts (for what purpose)?

A word of warning: Timeouts in distributed systems can be fraught with danger and difficulty. If used, they must be set and used very carefully because the indiscriminate use of timeouts does not fix a problem, it just defers the catastrophe. (If you want to see how timeouts should be used, read and understand the HDLC communication protocol documentation. This is a good example of suitable and clever use, in combination with a clever bit-coding system to allow detection of things like IDLE line).

For a time I worked in multi-processor distributed systems connected up using communication links (not TCP, something else). One of the things I learned was that as a rough generalisation, there are some dangerous multi-programming places to go:

reliance on queues usually ends in tears (if the queue fills, you are in trouble. UNLESS  you can calculate a queue size that will never fill, in which case you probably could use a no-queue solution)

reliance on locking is painful, try and think if there is another way (if you must use locking, look at the literature, multi-processor distributed locking has been the subject of many acedemic papers of the last 2-3 decades)

I you have to proceed using locking, then:

I will ASSUME that you will use timeouts only as a means of recovery of last resort - ie for detection of a failure of the underlying communications system. I will further assume that your TCP/IP communication system is high bandwidth and can be thought of as low latency (ideally zero, but this never happens).

What I would suggest is that every node has a connectivity list of other nodes it can connect to. (Nodes would not care where a connection comes from.) Population of the tables of which nodes a node can connect to is left as a separate thing to sort out, you have not said if that would be statically set or otherwise. Also conveniently ignored is things like the allocation of the IP port numbers where connections would come into a node - there can be good reasons for accepting requests on only a single port, or on multiple ports. This needs to be carefully considered. Factors will include implicit queuing, ordering, resource use, operating system type and capabilities.

Once nodes know who they connect to, they can send to that node a lock request, and must receive back from a lock reply from that remote node. You can pack those two operations into a wrapper to make it look atomic. The effect of this is that nodes wishing to acquire a lock will make a call something like:

```<code>if (get_lock(remote_node) == timeout) then
  {
    take some failure action - the comms network is down
  }

/* Lock is now acquired - do work here */

if (release_lock(remote_node) == timeout) then
  {
    take some failure action - the comms network is down
  }
</code>```

the calls get_lock and release_lock should be something like (in principle):

```<code>send_to_remote_node(lock_request)
get_from_remote_node_or_timeout(lock_reply, time)
if (result was timeout) then
  return timeout
else
  return ok
</code>```

You will have to take great care with a distributed locking system that the units of work performed while a lock is held are small and fast because you will have many remote nodes potentially held up waiting to get a lock. This is effectively a stop-and-wait multiprocessor / communication system which is robust but does not have the highest possible performance.

A suggestion is to take a completely different approach. Can you use a remote procedure call where each RPC call carries a package of information which can be handled by the recipient, and which removes the needs for locks?

On re-reading the question, it looks like you don't really want to be concerned with the communication side of things, you just want to solve your locking issue.

My answer might therefore seem a bit off-topic, however, I believe you can't solve your locking issue without getting the parts underneath it right as well. Analogy: Building a house on bad foundations causes it to fall down... Eventually.

Title: Looking for a distributed locking pattern

Body:
I need to come up with a custom recursive object locking mechanism\pattern for a distributed system in C#. Essentially, I have a multi-node system. Each node has exclusive write permissions over n-number pieces of state. The same state is also  available in read-only form on at least one other node. Some writes/updates must be atomic across all nodes, while other updates will eventually become consistent thru background replication processes, queues, etc...

For the atomic updates I'm looking for a pattern or samples that efficiently allow me to mark an object as locked for writes which I can then distribute, commit, rollback, etc... Since the system has high-levels of concurrency, I'm assuming I'll need to be able to stack-up locks which will either timeout or be unrolled once the locks are released.

The transaction or messaging pieces are not the focus of this question, but I've provided them for some extra context. With that said, feel free to articulate what messages you think would be needed if you like.

Here is a vague sample of what I was envisioning although I'm open to any new ideas aside from implementing whole new products

```<code>thing.AquireLock(LockLevel.Write);

//Do work

thing.ReleaseLock();
</code>```

I was thinking of using extension methods, which might look something like this

```<code>public static void AquireLock(this IThing instance, TupleLockLevel lockLevel)
{
    //TODO: Add aquisition wait, retry, recursion count, timeout support, etc...
    //TODO: Disallow read lock requests if the 'thing' is already write locked
    //TODO: Throw exception when aquisition fails
    instance.Lock = lockLevel;
}

public static void ReleaseLock(this IThing instance)
{
    instance.Lock = TupleLockLevel.None;
}
</code>```

To clarify a couple details...

All communications are TCP/IP using a binary request/response protocol

There are no intermediary technologies such as queues or databases

There is no central master node. In this case, the locking arrangement is defined by the initiator of the lock and the partner which will honour the request with some form of timeout to govern its behaviour

Anyone have any suggestions?

Body:
Seems to me like you have a couple of mixed technologies here:

communications (which you essentially rely on as being 100% reliable... which can be fatal)

locking / mutual exclusion

timeouts (for what purpose)?

A word of warning: Timeouts in distributed systems can be fraught with danger and difficulty. If used, they must be set and used very carefully because the indiscriminate use of timeouts does not fix a problem, it just defers the catastrophe. (If you want to see how timeouts should be used, read and understand the HDLC communication protocol documentation. This is a good example of suitable and clever use, in combination with a clever bit-coding system to allow detection of things like IDLE line).

For a time I worked in multi-processor distributed systems connected up using communication links (not TCP, something else). One of the things I learned was that as a rough generalisation, there are some dangerous multi-programming places to go:

reliance on queues usually ends in tears (if the queue fills, you are in trouble. UNLESS  you can calculate a queue size that will never fill, in which case you probably could use a no-queue solution)

reliance on locking is painful, try and think if there is another way (if you must use locking, look at the literature, multi-processor distributed locking has been the subject of many acedemic papers of the last 2-3 decades)

I you have to proceed using locking, then:

I will ASSUME that you will use timeouts only as a means of recovery of last resort - ie for detection of a failure of the underlying communications system. I will further assume that your TCP/IP communication system is high bandwidth and can be thought of as low latency (ideally zero, but this never happens).

What I would suggest is that every node has a connectivity list of other nodes it can connect to. (Nodes would not care where a connection comes from.) Population of the tables of which nodes a node can connect to is left as a separate thing to sort out, you have not said if that would be statically set or otherwise. Also conveniently ignored is things like the allocation of the IP port numbers where connections would come into a node - there can be good reasons for accepting requests on only a single port, or on multiple ports. This needs to be carefully considered. Factors will include implicit queuing, ordering, resource use, operating system type and capabilities.

Once nodes know who they connect to, they can send to that node a lock request, and must receive back from a lock reply from that remote node. You can pack those two operations into a wrapper to make it look atomic. The effect of this is that nodes wishing to acquire a lock will make a call something like:

if (get_lock(remote_node) == timeout) then
  {
    take some failure action - the comms network is down
  }

/* Lock is now acquired - do work here */

if (release_lock(remote_node) == timeout) then
  {
    take some failure action - the comms network is down
  }

the calls get_lock and release_lock should be something like (in principle):

send_to_remote_node(lock_request)
get_from_remote_node_or_timeout(lock_reply, time)
if (result was timeout) then
  return timeout
else
  return ok

You will have to take great care with a distributed locking system that the units of work performed while a lock is held are small and fast because you will have many remote nodes potentially held up waiting to get a lock. This is effectively a stop-and-wait multiprocessor / communication system which is robust but does not have the highest possible performance.

A suggestion is to take a completely different approach. Can you use a remote procedure call where each RPC call carries a package of information which can be handled by the recipient, and which removes the needs for locks?

On re-reading the question, it looks like you don't really want to be concerned with the communication side of things, you just want to solve your locking issue.

My answer might therefore seem a bit off-topic, however, I believe you can't solve your locking issue without getting the parts underneath it right as well. Analogy: Building a house on bad foundations causes it to fall down... Eventually.


答:
Again, this is only for my plant, and I'm the only one who will ever be supporting it unless I leave the company, and then my replacement would be supporting it. Not someone else already in the company.

1 -- Don't Assume you're the only one who's going to support this. You do like your sick time and vacation, right? What if you need to take extended maternity/paternity leave or something? Who's going to support your app then? Also, what if you'd like to talk to someone about technical problems specific to your company? What if you'd like to have code reviews? Or need help with a tricky bug? In all these cases it helps to be amongst others with insight into the technology you're using -- specifically how it can be applied to solve your company's specific problems.

The company does very little development with their standard anyway.

2 -- Just because some document exists doesn't mean its really the standard or means anything. It may simply mean that there's a group of politically influential individuals advocating this approach, and it may turn out there's other sub groups taking different approaches.

Your problem may simply be that the "standard" has evolved to some de-facto, undocumented state that conflicts with the documented "standard". Or there may be many little unofficial groupings of people using different "standards" -- with one of those groups managing to make their "standard" made official. You probably need to ask around to figure out what others in your group -- who might also support you and your app -- consider best practices. Ask what they feel comfortable with you using. Map out the real technology landscape of your company and figure out where the know how is. Just like any good piece of evolving tribal knowledge the only way you're going to know how to proceed is to talk to people.

3 -- Don't pass up professional opportunities to learn new things. You have to guard against being pigeonholed in this industry. Be nimble. You may have an opportunity to gain some breadth and learn a new way to solve a problem. Not to mention you're gaining new skills for your resume. It can mostly only help you to have to step outside your comfort zone to do something new. That being said, if the different/new thing is so extremely niche that you don't think you or any future employers will get any value from those skills, then maybe this isn't such a great opportunity. But getting a chance to be both an ASP.net and LAMP expert will certainly open your eyes and can only help your career. There's nothing like a real project with a deadline to force you to really learn something.

So my advice, don't go it alone. Figure out where people really stand and decide where you can best fit in. If you need to step out of your comfort zone, use this as an opportunity to grow professionally.


答:
Do you have any aspirations for promotion, or working on other projects? If so, I suggest that "doing your own thing" will have two negative effects almost certainly resulting in (paraphrase) "I will be the one supporting it, until I leave"

Because you chose not to follow the company standards shows you are not particularly suitable for more senior roles, as you are unable to follow simple instructions.

Because you chose not to follow the company standard, it will be your problem that no one else in the company can support your code.

If you choose to use the standard, it will not be your responsibility to continue to maintain the product when (if) an opportunity for promotion or another project arises.

The other way to look at a ludicrous analogy. I move to a country where they drive on the left, however, I am much more used to driving on the right, I prefer to drive on the right, because of this, I am better at it and can drive faster. Should I drive on the right?


答:
If you are porting a library to a new language, I would follow the naming conventions commonly used in that new language. This makes it easier for developers used to the conventions of the new language but not the original.

While the reverse domain name pattern is common in Java, for C# Microsoft's naming guidelines suggest something like YourName.TheLibrary or YourName.TechnologyProvidedByYourLibrary (see the article I linked to for details). I suppose there are similar guidelines for other languages as well.

Title: Package name best practice when porting a library

Body:
What is the suggested way (specifically in the open-source world) for the package name when porting a library.

Say I am porting someone else's library where they have used a reverse domain name stucture for there package name, so there library package name was some thing like com.therename.thelib. What should I do if I decide to port it to a new language? Should I keep the domain name intact, even though they didn't have a hand in it? Or should I change it to something like com.myname.thelib?


问:
Are design patterns independent of programming languages?
I have been recently working on Objective C and came across use of Delegate pattern.

I had seen most of the common patterns theoretically in Java, thanks to the Head First book.

But at times looking at differences in Dynamic and scripting languages I get confused about need of certain design patterns.

For example lets take example of Adapter pattern.

It already has two implementations : Object adapter[java] and Class Adapter[C++].
depending on whether the language has supports for Multiple inheritance or not.

But with dynamic languages like Objective-C, duck-typing is possible and also we have methods like respondsToSelector to check if an object actually supports a method or not.
So why do we have protocols here even if we need to use a delegate pattern ?

If we can assume anything to be anything.in a dynamic language, do we need concept of abstract class or interface at all to implement few patterns ?

they more look like tools for statically typed languages to give dynamic behavior.

specially I dont understand the need for abstract keyword in PHP.

Can anyone point out some important details, I am relatively new to this.

答: The main thing I get out of looking at Design Patterns is learning from other people's designs. They are not all applicable to all languages but studying them may teach you about a design you didn't understand or know before. Another benefit is, since we have named designs, we can talk about them more easily with other developers. Even if the pattern would be implemented differently in different languages it gives you tools to compare and contrast as well as present arguments on what situations work well with what designs, and maybe more importantly, which designs don't work with which situations.</p>

OwnerDisplayName: Amogh Talpallikar


问:
How to convert a copy/paste/spaghetti programmer to see the light?
This question was inspired by this one. While that other question was deemed localized, I believe the underlying problem is something that is extremely common in our industry. I know there are some developers, who will read this and think I'm making this stuff up and then they might reply how everyone cares about their work and wants to learn, but just looking at other Programmers SE posts (case in point), I know that's not universally true.

So let's say you have someone on your team (or maybe majority) who's standard operating procedure is to copy/paste and who believes that everything can be solved if only you add enough function calls and variables. This person never heard of TDD, DRY or SOLID and outside of 40 hours at work when they are busy working, they never once read a single methodology/pratices/design book.

In the past I (and others) have asked, how to do you teach OOD. But now I'm thinking that's not the right question. The real question is how do you approach such a person/team and make them curious about better way of doing things? How do you inspire them to learn?  Without that, it seems that all the teaching, meetings, lectures, discussions are useless if they are perfectly happy going back to their desk and doing what they've always done.

I work with a bunch of people like that. They are actually quite bright individuals, but I hate when I hear, "I'm done coding, just need to refactor and split into multiple classes to make DXM happy". They don't refactor for cleaner, readable, maintainable code, but only because otherwise they'll get scolded. I know they are capable of learning, just seems that there's a general lack of motivation.

When I deliver work, it generally has way fewer bugs and the work I owned never became 5000-line monstrosity of a class. Other's would make comments like, "your code is much cleaner and readable than our stuff", so they see the difference.  But at the same time, I feel like they believe they get paid for 40 hours regardless of what they do, so they actually don't mind if they spend 3 full days in QA looking for a bug that shouldn't have been introduced in the first place. Or that they take a week to modify one class because there are so many dependencies they end up touching.  The though, "maybe that class should have been written differently" never seems to pop up.

Can anything be done in these situations? Has anyone succeeded? Or is it best to isolate such mindset to non-critical parts of the project and minimize the damage?

NOTE: When I say "lack of motivation". I don't think it's lack of motivation to work or do a good job because they simply stopped caring.  Most of our team is actually quite the opposite. They definitely care about the product. We have guys that will work nights and weekends. The part I'm trying to get through is with improved habits and skills, they actually wouldn't have to work as much. I guess that "40 hours" thing made this post sound a little too negative.

答:
You found yourself the reason: "I know they are capable of learning, just seems that there's a general lack of motivation."

There are people who are passionate about their work. And there are others who, being sometimes competent enough, are working just for money. They know their stuff, but they don't enjoy their work. They will not spend extra time doing additional refactoring to make code readable or solving an intriguing problem when a quick and ugly hack can do the job.

This phenomenon exists in every job. It's just that some jobs are not extremely exciting (have you seen an accountant who loves his job and dreamed about it already when he was a child?), but in programming, there are plenty of people who really love what they are doing (otherwise Programmers.SE will be pretty empty). This means that as passionate developers, who talk daily to other passionate developers, we have more chances to be surprised seeing a person who does programming just for money.

What can we do? Not too much. In all cases, it's not to you, but to the human resources to choose people who are truly motivated¹. And fire people who are not.

You can try to motivate your colleagues yourself, but it's extremely hard. If you give them books to read, they will return them unopened a few weeks later. If you give them an advice, they will not listen, because they don't care².

You can:

Convince your boss to set a number of strict rules in your company: style guidelines, etc. This will not motivate those people to do a better job, but at least they will not be able to commit source code which doesn't match the requirements.

Work on the requirements, especially non-functional requirements. What about a requirement which tells that a specific project must contain less than 5 000 lines of IL code (no, I'm not talking about the meaningless LOC)³? What about requiring to obtain specific results at cyclomatic complexity or class coupling?

Increase the number of hours you spend in your company doing code reviews. Specify what is reviewed: if you have a checklist, add the points related to refactoring, readability, clean and useful comments, etc. If you don't have a checklist, you must.

Use [more] pair programming. It may help improve the code quality and motivate the less motivated coworkers.

Use the compensation system similar to what is used at Fog Creek.

¹ That's what interviews are about: before hiring you, the human resources must asset not only your technical level, but also your motivation. Sadly, some companies forget about this second part of the interview, and hire people who don't enjoy programming too much. Happily, in most cases, the work in those companies is never enjoyable, and Joel test rarely exceeds 2.

² They really don't care, even if they gain less money. I'm pretty close to one of my customers (I'm a freelancer) who believes that his work is to develop websites for his own customers. He also have a designer. I told them many times about the ways they can increase their productivity by 2 or more. If they just hired somebody competent, they would increase their revenue by at least 3. But they have enough money, and don't care about quality or how much they cost to the ignorant customers, compared to somebody productive.

³ What I mean is the number of lines of IL code which you see in Code Metrics in Visual Studio, the metric which actually means something. The real LOC doesn't matter and you don't have to measure it; it's one of the most stupid metrics ever. Enforcing IL lines of code means that developers will be forced to actually refactor code, and not just to collapse ten lines of code in a single unreadable line.


问:
Rule of thumb for cost vs. savings for code re-use
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.

答:
As you already pointed out, it does come down to balance.  In scientific/economics terms, you would evaluate the two sides of your decision, reusable code vs. app-specific hack and sum up the costs and benefits of each side and also take into account any probability values (e.g. the chance the code will actually be needed anywhere else).  In reality, we do these calculations subconsciously (using common sense, experience, gut feeling...) almost every day.

Technically, our designs should always be modular and reusable as much as possible, but there are plenty of instance where a "hack" as you put it, will take half a day to write vs. generic component a week.  In that case, I would take a stance of the YAGNI principle.

On the other hand, if a) you know there's 80-90% chance the code will be needed again, and it makes sense and b) it doesn't take significantly more time to make it reusable, then I say go ahead and design for reusability... and then for everything else there's the middle gray area :)

Also, in the past I've had success taking the middle ground between your two approaches.  I had projects where certain functionality could have been made reusable since day 1, but doing so would have incurred additional costs.  So instead, I kept all the code local.  In future work when the need for similar functionality arose, I went back to projects where this work was done originally, and at that time paid the extra cost of wrapping those classes into a reusable module.  Doing this gives you few advantages: 1) you don't pay extra cost until you need it and 2) later on when you do make a reusable component, you can leverage your knowledge of how well original code worked out in app-specific case and modify its design as needed before introducing it to "the world".

In some cases, original projects were never modified to use the new v2.0 reusable modules because original code already worked and with no active development it made no sense to modify that code. In other cases, once reusable components were tuned and improved, we went back and replaced custom implementations, but only after custom implementations actually required work to be done.  So one lesson from all this: even if you "hack" or write custom code, take an hour or two to come up with a clean interface.  In the future if you have to modify this code, that interface will make it that much more simpler to remove custom code and replace it with library calls.


答: The best practice is to write neat and understandable code irrespective of re-use purposes. A good written code can always find it's place in the future. You don't need to specifically write code in a manner which suits re-usage. All you need to do is follow good design principals and a bit of self-documenting code. This will make your code reusable itself.    </p>

Title: Rule of thumb for cost vs. savings for code re-use

Body:
Is it a good rule of thumb to always write code for the intent of re-using it somewhere down the road?  Or, depending on the size of the component you are writing, is it better practice to design it for re-use when it makes sense with regards to time spent on it.  What is a good rule of thumb for spending extra time on analysis and design on project components that have "some probability" of being needed later down the road for other things that may or may need this part.

For example, if I have the need for project X to do things A, and B.  A definitely needs to be written for re-use because it just makes sense to do so.  B is very project specific at the moment, and I can hack it all together in a couple days to finish the project on time and give everyone kudos for being a great team, etc.  Or if we say, lets spend a whole friggin' 2 weeks figuring out what project Y/Z might need this thing for and spend a load of extra time on on part B because someday we might need to use it on project Y/Z (where the savings will be realized).

I'd imagine a perfect world situation would be a nicely crafted combination of project specific vs. re-use architected components given the project.  However some code shops might feel it would be a great idea to write everything for the intention of using it at some point down the road.


答:
The real question is how do you approach such a person/team and make
  them curious about better way of doing things? How do you inspire them
  to learn? Without that, it seems that all the teaching, meetings,
  lectures, discussions are useless if they are perfectly happy going
  back to their desk and doing what they've always done.

That's it! This indeed is a real question.

To give some backgound, We simply don't have time to put in a lot of formal training - but occasionally if i do - it still see no light.I have also been part of the companies where formal training becomes a process itself but and i am so often a witness that they hardly teach them how to think.

So question that i pose to them is not how to teach them - but how to make them learn? The difference is subtle but it is what is going to make all the difference.

I don't know if i am right; but often i believe in a dialog of a Matrix the movie - "It's the question that drives us!" What is most important is to make them think, make them ask why! And of course, most who think they already know everything about some design patterns because they got good marks in university courses - are the most difficult there.

How do you get make them such questions?
My general approach is "that throw them in the pond if you want them to learn to swim". I agree that people may disagree; and i will gladly agree to disagree with them. When you throw them in the pond - they actually don't learn to swim automatically; but it sparks off a survival instinct that makes them think - once that happens they will naturally think of HOW and WHY.

A practical example i give folks is to put them in a significantly complex project than what they have hoped to get one on it and let them fight their own battle. As they begun to unravel the code and find it difficult to trace it through - you realize they start asking good question.

This may sound a bit extremist, this may sound waste of resource. And i am sure, there are many others who will give me the advice not to do this. But this has worked for me!

No matter what pay packages and HR tags you assign it wont solve basic motivation problem. For that only path is that they are challenged; If you spark of this basic human spirit - everything else works. If you cann't it's a loose loose game.

PS: Just incidentally i posted an answer here https://softwareengineering.stackexchange.com/questions/127021/how-do-you-train-freshers/127034 - and i got all the bashing; primarily most people believe that somehow businesses cann't afford to waste resources! I am sure, this answer may get similar treatment here. But the truth is, making people to work and making them believe in doing a good job is a subject of human psychology over how to craft the syllabus of the course.

Anyway, the task you are describing to here amounts to igniting the inner passion to do great change. And larger the system more difficult it gets. Begin with younger fellows who are still built in with i-won't-to-do-good-job spirit and challenge the status quo.

Title: How to convert a copy/paste/spaghetti programmer to see the light?

Body:
This question was inspired by this one. While that other question was deemed localized, I believe the underlying problem is something that is extremely common in our industry. I know there are some developers, who will read this and think I'm making this stuff up and then they might reply how everyone cares about their work and wants to learn, but just looking at other Programmers SE posts (case in point), I know that's not universally true.

So let's say you have someone on your team (or maybe majority) who's standard operating procedure is to copy/paste and who believes that everything can be solved if only you add enough function calls and variables. This person never heard of TDD, DRY or SOLID and outside of 40 hours at work when they are busy working, they never once read a single methodology/pratices/design book.

In the past I (and others) have asked, how to do you teach OOD. But now I'm thinking that's not the right question. The real question is how do you approach such a person/team and make them curious about better way of doing things? How do you inspire them to learn?  Without that, it seems that all the teaching, meetings, lectures, discussions are useless if they are perfectly happy going back to their desk and doing what they've always done.

I work with a bunch of people like that. They are actually quite bright individuals, but I hate when I hear, "I'm done coding, just need to refactor and split into multiple classes to make DXM happy". They don't refactor for cleaner, readable, maintainable code, but only because otherwise they'll get scolded. I know they are capable of learning, just seems that there's a general lack of motivation.

When I deliver work, it generally has way fewer bugs and the work I owned never became 5000-line monstrosity of a class. Other's would make comments like, "your code is much cleaner and readable than our stuff", so they see the difference.  But at the same time, I feel like they believe they get paid for 40 hours regardless of what they do, so they actually don't mind if they spend 3 full days in QA looking for a bug that shouldn't have been introduced in the first place. Or that they take a week to modify one class because there are so many dependencies they end up touching.  The though, "maybe that class should have been written differently" never seems to pop up.

Can anything be done in these situations? Has anyone succeeded? Or is it best to isolate such mindset to non-critical parts of the project and minimize the damage?

NOTE: When I say "lack of motivation". I don't think it's lack of motivation to work or do a good job because they simply stopped caring.  Most of our team is actually quite the opposite. They definitely care about the product. We have guys that will work nights and weekends. The part I'm trying to get through is with improved habits and skills, they actually wouldn't have to work as much. I guess that "40 hours" thing made this post sound a little too negative.


答: As you point out, its motivation.  Dont mistake them not caring for them not knowing.  They clearly know what to do.  They just dont care.  If thats the case, the real question here is... what is your management doing wrong that keeps them so unmotivated?  Are you the newest member of the team?  Perhaps they've been through all this before, with it only leading to problems from their management.  So they just stick to doing the very lowest amount of work needed to keep their job because they dont think doing more will be responded to by the employer.


问:
What is the Best Style for Functions with Multiple Returns and If/Else Statements?

Possible Duplicate:

  Elegant ways to handle if(if else) else

In a function where there are multiple returns, what is the best style to use?

This style, where there is no 'else' because it is frivolous and you think it is more concise?

```<code>f() {
    if (condition) {
        return value;
    }

    return other_value;
}
</code>```

Or this, if you think that 'else' provides nice syntax sugar to make it more readable?

```<code>f() {
    if (condition) {
        return value;
    } else {
        return other_value;
    }
}
</code>```

Feel free to share whatever other reasons you may have for preferring one over another.

EDIT:

The above samples are hypothetical, if they were this simple, as Yannis Rizos noted below, the ternary operator ( condition ? value : other ) would be acceptable. However I'm also interested in cases like this:

```<code>f() {
    if (condition1) {
        return value;
    } else if (condition2) {
        return value2;
    }
    ...
    else {
        return other_value;
    }
}
</code>```

答:
I prefer this one:

```<code>return (condition) ? value : other_value;
</code>```

but it's just a matter of personal preference. On any team I've worked I was happy to comply with whatever the code convention document preferred.

"Readability" is too vague a term to apply in such a specific and small issue and there's no technical reason to prefer one style over the others. Whichever one you feel is more readable, what matters most is to be consistent.

This StackOverflow question on Improving Code Readability gives some great points on other, more important, aspects of readability you should be concentrating on instead.

I got that the question was a hypothetical, but my answer still stands. It really doesn't matter.

On the expanded example, I prefer:

```<code>f() {
    if (condition1) {
        return value;
    } else if (condition2) {
        return value2;
    }
    ...

    return other_value;
}
</code>```

But for a very specific reason: I organize the blocks in such a way that the last one, the return other_value; is the one that's more likely to happen, so my code hints to business logic - and I'm not pretending that's smart. Still a strictly personal preference, the only reason behind it is my personal process of organizing code, one that I'd happily avoid if it goes against the team's conventions.

In any case, if you have more than a couple consecutive else if blocks, rewriting into a switch statement would probably make more sense, readability-wise.

Body:
I prefer this one:

return (condition) ? value : other_value;

but it's just a matter of personal preference. On any team I've worked I was happy to comply with whatever the code convention document preferred.

"Readability" is too vague a term to apply in such a specific and small issue and there's no technical reason to prefer one style over the others. Whichever one you feel is more readable, what matters most is to be consistent.

This StackOverflow question on Improving Code Readability gives some great points on other, more important, aspects of readability you should be concentrating on instead.

I got that the question was a hypothetical, but my answer still stands. It really doesn't matter.

On the expanded example, I prefer:

f() {
    if (condition1) {
        return value;
    } else if (condition2) {
        return value2;
    }
    ...

    return other_value;
}

But for a very specific reason: I organize the blocks in such a way that the last one, the return other_value; is the one that's more likely to happen, so my code hints to business logic - and I'm not pretending that's smart. Still a strictly personal preference, the only reason behind it is my personal process of organizing code, one that I'd happily avoid if it goes against the team's conventions.

In any case, if you have more than a couple consecutive else if blocks, rewriting into a switch statement would probably make more sense, readability-wise.


问:
Should one use pseudocode before actual coding?
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?

答:
No, do not pseudo-code first

This is too much overhead.  You're doing the work of writing the logic with none of the benefits.  I'd suggest any of the following instead:

Prototype in the language you're going to ship with (AKA Write one to throw away)

Architecture diagrams w/ code snippets to test assumptions / key designs

Test Driven Development where you write your interfaces/code structure first, followed by tests, followed by implementing the code.

All three of these move you directly towards your solution, unlike pseudo-code.  Personally I tend to use techniques 1 or 2 depending upon team size.  For smaller (e.g. 5 people or less) teams, prototyping works very well.  For larger teams that have multiple groups of developers working in parallel, I've found that documentation produced early by technique 2 works well because it gives you something to discuss early and helps you define component boundaries better.  I'm sure TDD would work very well too, but I have yet to work on a team which had committed to this process.


答:
I like what Uncle Bob wrote in Clean Code.  It was something along the lines that when you write clean and readable code, your functions should be small enough (and obviously fit on a single page) that you shouldn't need these type of guidelines or style specifications.

Instead your #1 objective is to improve readability as much as you can. As long as its readable and clear, anything else is just a personal preference.  I'm assuming the example you supplied was just a hypothetical example but if it was actual code, then Yannis definitely gave you a more readable alternative.

Title: What is the Best Style for Functions with Multiple Returns and If/Else Statements?

Body:
Possible Duplicate:

  Elegant ways to handle if(if else) else

In a function where there are multiple returns, what is the best style to use?

This style, where there is no 'else' because it is frivolous and you think it is more concise?

```<code>f() {
    if (condition) {
        return value;
    }

    return other_value;
}
</code>```

Or this, if you think that 'else' provides nice syntax sugar to make it more readable?

```<code>f() {
    if (condition) {
        return value;
    } else {
        return other_value;
    }
}
</code>```

Feel free to share whatever other reasons you may have for preferring one over another.

EDIT:

The above samples are hypothetical, if they were this simple, as Yannis Rizos noted below, the ternary operator ( condition ? value : other ) would be acceptable. However I'm also interested in cases like this:

```<code>f() {
    if (condition1) {
        return value;
    } else if (condition2) {
        return value2;
    }
    ...
    else {
        return other_value;
    }
}
</code>```


答:
Companies have standards for a reason, if there is a formally stated standard that says to use x, then youu need to justify y.

This doesn't mean that you can't use y, it does mean that you should understand the reasoning behind the standard and and get approval before violating it.

Perhaps after you understand why, you'll no longer want to violate it, perhaps you'll see that it needs to be changed or scrapped, or that it doesn't apply in this instance so that using y isn't a problem.

If it applies, then unless you can get it changed, you should follow it. Company standards aren't quite on the same level as direct orders, but your employer has a reasonable expectation of you following both unless they violate the law.


问:
How to spread awareness for generic programming among team members?
I am staying in an environment, where people believe:

Java generics are the feature exclusively used for library writing
and not for the real coding.

C++ is an OO programming language; template is an optional and
avoidable feature

Though, these people rely highly on the libraries written using generic programming (e.g. STL, Java containers). If I write a code using templates or generics, the code reviewer is most likely to reject it and will comment to write it in a "proper / understandable / elegant" way.

Such mentality is applicable from normal programmer to senior most manager. There is no way out, because 90% of the time, these people have their lobbying.

What is the best way (not being cut throat) of explaining them, the practical approach of writing code which constitutes OO and generic programming both at the same time ?

答:
There are always several ways of doing the same thing. If your use of templates is a misuse of templates then it should fail the code review.

However, if your code fails the review, because they do not understand templates, then the problem is of different sort. In that case advise them (in a nice way) to learn templates.


答:
Of course, as others have pointed out it is mostly a matter of personal preference. The key word here being mostly. There are, however, some objective guidelines that can be used, and personally, I like forming my personal preferences based on objective guidelines, regardless of how insignificant these may be.

So, the way I do it is as follows:

```<code>if( condition )
    return;
do-other-stuff;
</code>```

And I always code multiple-if-else statements as follows:

```<code>if( a ) return x;
if( b ) return y;
if( c ) return z;
return null; //whatever, I ran out of letters
</code>```

And here is why:

Deep down at the assembly language level, the 'else' keyword corresponds to some code. An if-then-else statement in assembly language looks like this:

```<code>    test condition
    if false, jump to else
    perform the if-part
    jump to end
else:
    perform the else-part
end:
</code>```

The 'jump to end' instruction can be thought of as the code that the 'else' part corresponds to. Now, consider how the above code fragment changes when the if-part is a return statement:

```<code>    test condition
    if false, jump to else
    do-some-stuff-and-return
    jump to end
else:
    perform the else-part
end:
</code>```

Clearly, the 'jump to end' instruction will never be executed. I would be willing to bet that when a compiler analyzes your code to find unreachable code, it does figure out that the 'else' keyword is unreachable, and it factors it out, but it refrains from issuing a warning because this style is used by many out there, and it does not want to upset them. But I use this as an objective justification, no matter how insignificant it is, for never using the 'else' keyword when the if-part returns.

Body:
Of course, as others have pointed out it is mostly a matter of personal preference. The key word here being mostly. There are, however, some objective guidelines that can be used, and personally, I like forming my personal preferences based on objective guidelines, regardless of how insignificant these may be.

So, the way I do it is as follows:

if( condition )
    return;
do-other-stuff;

And I always code multiple-if-else statements as follows:

if( a ) return x;
if( b ) return y;
if( c ) return z;
return null; //whatever, I ran out of letters

And here is why:

Deep down at the assembly language level, the 'else' keyword corresponds to some code. An if-then-else statement in assembly language looks like this:

    test condition
    if false, jump to else
    perform the if-part
    jump to end
else:
    perform the else-part
end:

The 'jump to end' instruction can be thought of as the code that the 'else' part corresponds to. Now, consider how the above code fragment changes when the if-part is a return statement:

    test condition
    if false, jump to else
    do-some-stuff-and-return
    jump to end
else:
    perform the else-part
end:

Clearly, the 'jump to end' instruction will never be executed. I would be willing to bet that when a compiler analyzes your code to find unreachable code, it does figure out that the 'else' keyword is unreachable, and it factors it out, but it refrains from issuing a warning because this style is used by many out there, and it does not want to upset them. But I use this as an objective justification, no matter how insignificant it is, for never using the 'else' keyword when the if-part returns.


答:
Obligatory XKCD #974:

In my experience, trying to always make everything reusable may lead to over-engineering.

However, a certain non-excessive amount of effort to make things reusable is always worth trying to put into things, (when things are amenable to reusability,) because a reusable component is a general purpose component, which means that its interface is abstracted, which means that it is easier to understand it on its own, and figure out how it works and why it works, and what it does and how it does it, when you look at it on its own, or when you look at it 6 months down the road and you don't even remember ever having written it. And these benefits are of course in addition to the fact that it is reusable.

So, to cut a long story short, I believe that the rule of thumb should be:

Make it reusable if doing so will make its interface and / or its implementation easier to understand.


答:
This is a specialized form of the more general question "how do you convince your superiors to start making use of a newer and better technology / way of making things?"

Unfortunately, I do not think you can, and I am not sure you should. It is by definition their choice, since they are paying you to do things in a certain way that they have chosen, not in any way you like.  The best you can do is suggest that this technology is out there, lots of people are using it, and it appears to be the way of the future. You might even want to mention the fact which they of course ought to know already: that it is best for people to not let their skill set stagnate. But that's it: if they don't buy it, there is nothing you can do.

They may have other considerations which you do not have, because you are not thinking at their level.  You are thinking as an engineer, they may be thinking more in business terms or even human resources terms.

Will generics (or whatever) improve the value of their product? Probably not.

Will generics (or whatever) make it harder for the people that they have already hired to do their job? Yes.

Will generics improve time-to-market? If the only engineer was you, maybe. But if a whole bunch of engineers need to be educated on generics before another line of code is written in the house, No.

So, you might want to consider just changing jobs.  In my last job I was the first to use generics with Java, and luckily they did not have a problem with it; they expressed a concern that generics make code 'harder to read', but they let me have my way. Find a job like that.

Title: How to spread awareness for generic programming among team members?

Body:
I am staying in an environment, where people believe:

Java generics are the feature exclusively used for library writing
and not for the real coding.

C++ is an OO programming language; template is an optional and
avoidable feature

Though, these people rely highly on the libraries written using generic programming (e.g. STL, Java containers). If I write a code using templates or generics, the code reviewer is most likely to reject it and will comment to write it in a "proper / understandable / elegant" way.

Such mentality is applicable from normal programmer to senior most manager. There is no way out, because 90% of the time, these people have their lobbying.

What is the best way (not being cut throat) of explaining them, the practical approach of writing code which constitutes OO and generic programming both at the same time ?


问:
How to build a .Net app which runs on desktop and as a Windows Service
Ok, I hope this is not too much confusing (with my poor English). I want to build a small .Net 4.0 app which monitors several other applications on a Windows Server OR on a regular Windows PC. It will have a WPF GUI with a variety of graphical controls.

The app will be used in the following scenarios:

If installed on a PC it should run as a “normal” single Windows
desktop app

If installed on a Server, it should run as a Windows Service.  To use/manage the app it must have the same WPF GUI as in scenario 1 and the GUI should be run on the Server or on a remote PC

At the moment I consider to write the application logic and connect it to the WPF GUI using a self-hosted WCF Data Service IN BOTH SCENARIOS. Since I’m not a pro developer I suppose it’s possible that I've missed something ;-)

Will this work? Are there other/better solutions? Any answer or comment is highly appreciated.

答:
This is an interest question, and It is similar as a project which is under progressing.

we have requirement to monitoring a ini file changed event, the ini file is a output of a hard device, whenever the ini file changed, we need read all information from the file and store them into a file database. Then we should provide a GUI to view the file database.

What I choose to use is creating a Windows Service to WCF lib which can provide inter process comm and creating a windows form as GUI to consume WCF interface.

Hope this can give you a hint.


答: It all depends on whether you are going to get fired or not. If you are going to get fired, don't do it. If you are not going to get fired, then by all means go ahead with it.</p>


答:
I would broadcast the merits of generics to the code reviewer and other colleagues ahead of any review:

1) By allowing you to specify types that are acted on by a generic class or method, the generics feature shifts the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.

2) Generics provide type safety without the overhead of multiple implementations.

So, [1] and [2] reduce the risk of error in the code. This saves the developer time and therefore the company money.

If readability is an issue then the awkwardness of using generic types could be compromised. This is one reason you might want to extend coding guidelines. This can be done in a workday context and not just for extending libraries (however, it's an idea to refactor as you go and mark possible candidate methods for libraries in the code for easy recognition later). Therefore, there would be no reason not to use them in a workaday context.

I would add a few statements about how other programmers do not have issues with generics: Generics are widely used in Java and many other languages like C#. Any serious programmer would find life difficult without such type safe building blocks.

Nonetheless, you may want to consider that some of the developers may not be up to scratch. Management could have made a conscious decision to protect projects in the past, thereby keeping these chaps out of dangerous areas. Here, both the innocent and the guilty usually get the blame as sufficient analysis or micro-management is rarely conducted.

If you put a good case forward and you are not given a reasoned response in return then secretly begin to look for another company that takes programming seriously.