答:
I don't know if your status example is real code or here just for the sake of demonstration, but it seems odd to me that you should implement Status as an Entity (not to mention an Aggregate Root) when its ID is a constant defined in code - Constants.Status.OutstandingId. Doesn't that defeat the purpose of "dynamic" statuses you can add as many of as you want in the database ?

I'd add that in your case, the construction of a Task (including the job of getting the right status from StatusRepository if need be) might deserve a TaskFactory rather than staying in the Task itself, since it is a non-trivial assemblage of objects.

But :

I am consistently told that entities should not access the
  repositories

This statement is imprecise and oversimplistic at best, misleading and dangerous at worst.

It's quite commonly accepted in domain-driven architectures that an entity shouldn't know how to store itself - that's the persistance ignorance principle. So no calls to its repository to add itself to the repository. Should it know how (and when) to store other entities ? Again, that responsibility seems to belong in another object - maybe an object that is aware of the execution context and overall progress of the current use case, like an Application layer service.

Could an entity use a repository to retrieve another entity ? 90% of the time it shouldn't have to, since the entities it needs are usually in the scope of its aggregate or obtainable by traversal of other objects. But there are times when they aren't. If you take a hierarchical structure, for instance, entities often need to access all their ancestors, a particular grandchild, etc. as part of their intrinsic behavior. They don't have a direct reference to these remote relatives. It would be inconvenient to pass these relatives around to them as parameters of the operation. So why not use a Repository to get them - provided they are aggregate roots ?

There are a few other examples. The thing is, sometimes there's behavior you can't place in a Domain service since it seems to fit perfectly in an existing entity. And yet, this entity needs to access a Repository to hydrate a root or a collection of roots that can't be passed to it.

So accessing a Repository from an Entity is not bad in itself, it can take different forms that result from of a variety of design decisions ranging from catastrophic to acceptable.

Title: Accessing Repositories from Domain

Body:
Say we have a task logging system, when a task is logged, the user specifies a category and the task defaults to a status of 'Outstanding'. Assume in this instance that Category and Status have to be implemented as entities. Normally I would do this:

Application Layer:

```<code>public class TaskService
{
    //...

    public void Add(Guid categoryId, string description)
    {
        var category = _categoryRepository.GetById(categoryId);
        var status = _statusRepository.GetById(Constants.Status.OutstandingId);
        var task = Task.Create(category, status, description);
        _taskRepository.Save(task);
    }
}
</code>```

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, Status status, string description)
    {
        return new Task
        {
            Category = category,
            Status = status,
            Description = descrtiption
        };
    }
}
</code>```

I do it like this because I am consistently told that entities should not access the repositories, but it would make much more sense to me if I did this:

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, string description)
    {
        return new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };
    }
}
</code>```

The status repository is dependecy injected anyway, so there is no real dependency, and this feels more to me thike it is the domain that is making thedecision that a task defaults to outstanding. The previous version feels like it is the application layeer making that decision. Any why are repository contracts often in the domain if this should not be a posibility?

Here is a more extreme example, here the domain decides urgency:

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, string description)
    {
        var task = new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };

        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            task.Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }

        return task;
    }
}
</code>```

There is no way you would want to pass in all possible versions of Urgency, and no way you would want to calculate this business logic in the application layer, so surely this would be the most appropriate way?

So is this a valid reason to access repositories from the domain?

EDIT: This could also be the case on non static methods:

```<code>public class Task
{
    //...

    public void Update(Category category, string description)
    {
        Category = category,
        Status = _statusRepository.GetById(Constants.Status.OutstandingId),
        Description = descrtiption

        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }

        return task;
    }
}
</code>```


问:
What does "windowed streaming" stand for?
So I was asking around the Mercurial development mailing list about binary diffing and patch handling and I got the following examples:

whole file approaches (classic diff, bsdiff, Mercurial's internal
bdiff)

windowed streaming approaches (rsync, xdelta, libxdiff)

What does "windowed streaming" stand for in this context? (and in general)

答: I believe that it's an ad-hoc expression to describe the algorithm used by rsync which is based primarily on a rolling hash. It is an extremely fast way to compute diffs, but works in blocks and doesn't handle smaller changes optimally.</p>

ContentLicense: CC BY-SA 3.0


问:
Case insensitive keywords in a language
We're trying to write a custom scripting language. There has been a suggestion to make the language forgiving by providing case insensitive keywords.

I personally do not like the idea, but there are few people in my team leaning towards it, saying it will make the end user happy! Examples of languages like FORTRAN, BASIC, SQL are given saying that these are case insensitive.

Is this a good idea?

答:
Programming languages should be case-sensitive, period. People can adjust to this very easily: they simply have to remember to work mostly in lower case, and to watch out for mixed-case or all-caps identifiers in existing API's.

It once seemed obvious to make languages case-insensitive. This is because lower case was not available on all computing systems and their I/O devices (keyboards, printers and display devices). Programming language implementations had to accept programs written in upper case, since only that could be displayed or printed. And for that they had to be case insensitive, because to accept upper case and be case sensitive at the same time means to reject lower case. Lower case was something programmers wanted, but could not always have. Nobody really wanted to work with programs which shouted in upper case; it was just a hardware limitation.

For a while, it was common to even do case folding in terminals. If a terminal could only display upper case, but you had to log into a computing system supporting upper and lower case, the terminal would fold the lower case to upper case. Think this was so long ago? "Like the Apple II, the Apple II Plus had no lowercase functionality." (http://en.wikipedia.org/wiki/Apple_II_Plus)  When users of early Apple computers dialed into a BBS that had mixed-case content, the terminal emulator (or host) had to fold that all to upper case. Messages written in all caps were common on bulletin boards in those days. This functionality is still found in Unix-like operating systems, like the Linux kernel. For example, type the stty olcuc at your shell prompt. The Unix tty line discipline can map lower case to upper on output, and it can map upper case to lower on input. This allows you to work in a lower case programming language, on a terminal that has no lower case.

Case insensitivity is an outdated concept from a bygone computer era that doesn't work very well in the modern world of internationalized computing. Do you extend that into other languages? How about French: do you consider È and è to be equivalent?  Or Japanese? Do you consider hiragana and katakana to just be cases, so that ファイル and ふぁいる are the same identifier? Support for such folly will greatly complicate your lexical analyzer, which will have to have case equivalence maps for the entire Unicode space.

Note that mathematics is case sensitive. For instance, the upper case sigma might denote summation, whereas the lower case sigma denotes something else, like standard deviation.
This can occur in the same formula without creating any difficulties. (Will the programming language make Σ and σ equivalent?)

English orthography is sensitive. For example, many proper nouns correspond to ordinary nouns or even other parts of speech. "may" is a verb, but "May" is a month, or a woman's name.  Moreover, if an acronym or abbreviation is written in lower case, it can be confusing. SAT stands for scholastic aptitude test, whereas "sat" is the past participle of "sit". Intelligent people pay attention to detail and capitalize properly.

Basicaly, any new programming language created since 1985 which is case-insensitive is FOR THOSE WHO STILL SHOUT IN E-MAILS AND POSTINGS WITHOUT A SECOND THOUGHT.

What if your language is ever used as a code-generation target to translate code in another language, and that other language is case sensitive? You will have to somehow transform all the names to capture the distinction. (So to assert that this is not a technical decision, and only matter of the emotional preferences of the target audience, is ridiculous.)

Look at the annoying problems caused by case handling in the Windows, when files are imported from another operating system. That's a technical issue.   Case sensitive file systems have a problem with foreign data which case-insensitive ones do not.

Common Lisp has hit upon the ideal approach: symbol names are case sensitive, but when tokens are read, they are folded to upper case. This means that the tokens foo, fOO, FOO and Foo all denote the same symbol: the symbol whose name is stored as the character string "FOO". Furthermore, this behavior is only the default read table configuration. The reader can fold letters to upper case, to lower case, invert the case, or preserve it. The last two choices give rise to a case-sensitive dialect. This way, users have the maximum flexibility.

Title: Case insensitive keywords in a language


问:
Tips on persuading boss that code review is a good thing
Let's say one works in a hypothetical company that has several developers that rarely worked together on projects and the Boss didn't believe that code reviews are worth the time and cost.

What are various arguments that could be presented in this scenario that will portray the benefit of code review?  Furthermore, what are the potential arguments against code review here and how can these be countered?

答:
Lots of great answers here. Some things I would add:

When you have to explain code to someone else, often in the course of the explanation the developer may suddenly realize he has a bug. I've seen it happen again and again that the dev stops dead in his tracks and says "oh wait that's wrong" before the reviewer has understood the thing well enough to see the bug.

Knowing your code will be inspected by someone else gives you more incentive to use coding standards (making maintenance easier) or use less "cowboy" methods that no one except yourself (and sometimes not even yourself) will ever understand. You don't want to be embarrassed when you show your code to someone else, so you do a better job on it in the first place. Because of the embarrassment factor, it leaves less of the code commented with:
"I don't know why this works but don't mess with it." in the code base.

Developers who have the need for more extensive supervision or training are easily identified. So are the outright incompetent. The sooner you can find and address performance problems, the better off the team as a whole and the higher the quality of the application will be. It's good to find out this information before you take the new guy who needs training and assign him to the hardest, most critical part of your application.

Sometimes it is just a matter of correcting a misperception that will save making the same mistake in a bunch of other places. For instance we were recently reviewing some SQL for complex reports and found that several of our new devs had the same misunderstanding about where to find a specific piece of information in the database (admittedly the place they picked seemed logical which is a database design issue we also need to fix) that would be critical to correctly writing all the reports. By finding the problem and correcting it in the first reports they wrote, it saved the same error from happening in the rest of the reports. And something the older (in time working here not age) devs were so used to that they didn't think it needed explaining came out. It also made us realize there were some other things we probably needed to make sure the newer devs were up-to-speed on.

Juniors can learn from the more sophisticated code written by seniors (who tend to better understand error trapping and edge cases for instance) and seniors can learn from the new techniques used by juniors that they haven't been exposed to yet.

Sometimes people working on different but related parts of the application realize that they are going in two different and mutually exclusive directions. Ooops, easier to fix now.

It's not so easy to sneak in hard-coded values that will change over time just to get the thing to work now. This prevents a lot of future bugs such as things which change at the beginning of each fiscal year.

I've sometimes been stuck on how to do something and learned a new technique that was just what I wanted from code reviewing someone else's stuff.

If you are familiar with how the other members of your team think (which code review will help give you that understanding), then it will be easier to troubleshoot problems later because you will start with an understanding of how Joe would have approached that kind of problem.


问:
Are dynamic languages at disadvantage for agile development?
From what I've read agile development often involves refactoring or reverse engineering code into diagrams. Of course there is much more than that, but if we consider the practices that rely on these two methods, are dynamically typed languages at disadvantage?

It seem staticly-typed languages would make refactoring and reverse engineering much easier.

Is Refactoring or (automated) reverse engineering hard if not impossible in dynamically typed languages?
What does real world projects tell about usage of dynamically typed languages for agile methodology?

答:
Your principles thought sounds to me correct.

The strongly-typed languages like C# are good candidates for a code base that constantly needs re-factoring. Basically most re-factoring tools (like Resharper, JustCode, etc..) in the market are very effective in statically typed programming languages.

What does real world projects tell about usage of dynamically typed languages for agile methodology?

For development team that practices Agile/Scrum methodology it is very helpful (even critical) to have good set of re-factoring tools under armor. Otherwise, all sudden changes in upcoming sprint may be a nightmare to be modify or re-design.

Thus, agile methodology does not provide advantages to statically typed languages or dynamic once. What it provide is an iterative approach to build a solid application.


答:
Automated refactoring was invented in Smalltalk, a dynamically typed language. So no, its not impossible to have automated refactoring in a dynamically typed language. How hard it is depends far more on other factors besides the typing discipline. C++ and Java are both statically typed, but refactoring tools only really exist for Java. Smalltalk with its introspection and simple syntax was a really good candidate for refactoring tools.

In some ways, dynamic typing actually makes refactoring easier. If you have a good testing suite, you can be sure your refactorings haven't broken anythings. A dynamically typed code base is typically smaller. Additionally, refactorings tend to affect less code. Altogether the effort involved in manually refactoring a dynamic code base is less then that of a static code base.

Title: Are dynamic languages at disadvantage for agile development?

Body:
From what I've read agile development often involves refactoring or reverse engineering code into diagrams. Of course there is much more than that, but if we consider the practices that rely on these two methods, are dynamically typed languages at disadvantage?

It seem staticly-typed languages would make refactoring and reverse engineering much easier.

Is Refactoring or (automated) reverse engineering hard if not impossible in dynamically typed languages?
What does real world projects tell about usage of dynamically typed languages for agile methodology?


答:
Refactoring was invented in dynamic languages. Automated Refactoring Tools were invented in dynamic languages. IDEs were invented in dynamic languages. Several Agile Methodologies were invented in dynamic languages.

I really don't see any problem.


问:
IPC in C under linux
I'm building a messaging solution with the followingsetup: all the messages are saved on a DB, two or more reader processes will read from this DB and send data to other process(es) which will send it over the network.

My approach is depicted below,

The following have 4 sender process with 4 fifos, and 2 readers with 2 fifos

reader0 ← read data from DB

reader1 ← read data from DB

sending part

network_handler0 ← network_handler_fifo0 ← reader0

network_handler1 ← network_handler_fifo1 ← reader1

network_handler2 ← network_handler_fifo2 ← reader0

network_handler3 ← network_handler_fifo3 ← reader1

receiving part

network_handler0 → reader_fifo0 → reader0 → write to DB

network_handler1 → reader_fifo1 → reader1 → write to DB

network_handler2 → reader_fifo0 → reader0 → write to DB

network_handler3 → reader_fifo1 → reader1 → write to DB

I have few problem with this setup, and please note that the number of processes could be more than that based on the environment, so I could make it 20 readers and 10 network_handlers or it it could as shown above.

The size of the buffer is 64K and the message size is 200k, is this small enough to make the write/read to/from fifo atomic?

How can make the processes aware of each other, so for example, reader 0 writes to network_handler_fifo0 and network_handler_fifo2, how can I make it start writing on other fifo if the current ones are full or their network_handlers are dea
d

I thought about making the reader process writing more general in writing, so for example it writes to all network fifos using lock mechanism and stop writing on the one that its process dead, I didn't use it as lock mechanism could slow thing down.

BTW, each network_handler is an SCTP association, so network_handler0 is association 0, network_handler1 is association 1 and so on.

Any idea is appreciated. I mean even if I have to change the setup above.

答:
It looks like your design might be a multithreaded client/server similar to the linked Code Project example.  For the sake of efficiency, you might consider using a thread pool.  You will need to protect your resources from multiple access even if you were dealing with just one byte, let alone a FIFO.  I am not sure from your description whether this is a hardware or software FIFO, but I would expect you must control access to it on a per message basis.

Andrew Tannebaum used to recommend that you use queues for communication and processes for concurrency.  Is there a reason that the reader and sender are two separate processes?  Do you actually have separate processes or separate threads (i.e. the threads are part of a process and share memory)?

The classic Readers and Writers problem gives some advice on what to do with reads and writes for your database.  The problem is not easy, but is explained in layers and the solution given on Wikipedia is worthy of emulation.  One of my professors from grad school has a readers and writers page well, and shows multiple solutions.  He gives a collection of pthreads based examples (including the consumer/producer problem).

Also included is a sem.c/.h wrapper library for pthreads that permits easier translation of example algorithms that use P() and V() that you might find sprinkled around the internet.  P() and V() are semaphore functions as notated by Dutch computer scientist Edsger Dijkstra selected based on Dutch words as explained on Wikipedia.  Sometimes semaphore functions are named signal() and wait(), which though clearer for English speakers, differs from what is used in a lot of research.

If you find that you have a dead process that you need to abandon, if you are using hardware FIFOs, it sounds like you lose them too.  If a network resource goes down, that is something that definitely needs attention.  Timeouts are kind of a bane of existence that makes sound, elegant algorithms into confused and unreliable implementations.

WRT the streaming aspects, somewhere in your algorithm you might want to drop packets in an evenly spaced fashion.  I found a paper by researchers from MIT and Brown about streaming that might be of interest.

Title: IPC in C under linux


问:
Is taking frequent breaks really that beneficial when programming?
I keep reading that it is recommended for a programmer to take frequent breaks while programming, and the usual recommendation I see is 5 minutes every half hour or 10 minutes every hour.

I gave it a try, but quite often I find something interesting during those 5 minutes, and it takes me away from what I was working on for longer than I planned. Either that, or my mind gets focused on something else and I find it hard to get back into my work and don't focus very well.

Is it really that beneficial to take frequent breaks while programming? Am I doing something wrong for it to be decreasing my productivity instead of increasing it?

答:
I find the option of frequent breaks very helpful.  If I'm neck-deep in a task rolling along, I might go hours without a break.  I would certainly find a forced break very disruptive.

If I'm working on code that just isn't behaving, walking around for a few minutes lets my brain wander "around" the problem enough to give an insight to the problem.

I often joke that my best thinking for the job goes in in the company's bathroom, but it's only half-kidding.

ContentLicense: CC BY-SA 2.5


问:
How do you explain refactoring to a non-technical person?
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)

答:
Take your desktop computer for instance. You have a tower, monitor, keyboard, mouse, printer, scanner and speakers. Ultimately all you want is a nice organized desk. So you just plug things in blindly, and a few minutes later, lo and behold, everything is set up the way you want it. Well... almost the way you want it.

A day later when you are changing the balance on your speakers, you realize you accidentally put your left and right speakers in the wrong areas, so you want to swap their positions. But oh no! There is a jungle of tangled cords; when you proceed to move the speakers, your mouse cord gets hooked, and now your mouse gets dragged along with the speakers. Also, your keyboard now doesn't have any slack -- you used to be able to move it from the desk onto your lap.

Alright, you could just unplug the mouse and keyboard and reinsert them so everything is fixed. But this won't help with future reorganization and future additions. Also weaving your mouse and keyboard cords through the jungle is a hassle.

The better solution is to replug everything to plug them back in a neat clean way where each cord does not interfere with another. Now future changes are easy and continue to be easy. You invest a little up front for big gains later.

The key point is that the original solution mostly WORKED. That's the thing about refactoring: it works to begin with, but you need to change how things already exist to easily make future changes (moving the speakers).


问:
How to explain why design choices are good?
As I've become a better developer, I find that much of my design skill comes more from intuition than mechanical analysis. This is great. It lets me read code and get a feel for it quicker. It lets me translate designs between languages and abstractions much easier. And it lets me get stuff done faster.

The downside is that I find it harder to explain to teammates (and worse, management) why a particular design is advantageous; especially teammates that are behind the times on best practices. "This design is more testable!" or "You should favor composition over inheritance." go right over their heads, and lead into the rabbit hole of me trying to clue everyone in to the last decade of software engineering advances.

I'll get better at it with practice of course, but in the mean time it involves a lot of wasted time and/or bad design (that will lead to wasted time fixing it later). How can I better explain why a certain design is superior, when the benefits aren't completely obvious to the audience?

答:
This may not directly answer your question, but it might lead you in an interesting direction.

I think what you need to do is more related to selling them on the idea than explaining it to them. Sales is all about understanding what the customer's problem is and then showing them how your product (or development method, whatever) will benefit them. Each person has different needs, so those things that benefit one person and gets them excited may very well leave another person cold.

For your CEO time-to-market may be the key, for your manager it might be more predictable schedules, for your programming colleagues it might be faster coding (or easier testing / documentation / debugging / whatever), and for your company's customers it might be ... ?

Sales does not happen automagically -- you have to make a concerted effort to understand the other person's point of view, and then figure out how to map your ideas into their Happy Place™. Once they know how they will personally benefit from this new thing, they often ask, "How much will it cost and how soon can we do it?" Once you hear those magic words you know you have done your sales job well.


答:
Being the sole voice of change is never an easy thing. The first challenge is usually to get other people on board with you (Hopefully there are some in your company who are more open minded than the rest).   If you can grab the attention of a couple other senior developers/managers to join your crusade, those combined voices will be ever harder for the rest to ignore.

I find a good way to explain to people is through providing concrete examples of past mistakes made in projects which they have been actively involved in (e.g. "Have you ever tried to debug this thing?   It's been like this for years and noone knows how to fix it..").  Better still, applying those 'new' design ideas and principles to a small/trial project and being able to show off how successful it's been at the end.

Depending on the attitudes of others in your company, change may come quickly, or it may be like trying to swim through treacle.   Some managers are completely immovable unless they have solid statistics/proof in front of them, where others are quite keen to be keeping up with the latest thinking.

You might need to try different tactics depending on who you're dealing with;   Suggesting that money/time/effort might be saved and quality might be improved is a good way to grab the attention of non-technical managers;    and the promise of easy automated testing appeals to quite a lot of developers who usually can't stand spending days running through the same test spreadsheets repeatedly.

Title: How to explain why design choices are good?

Body:
As I've become a better developer, I find that much of my design skill comes more from intuition than mechanical analysis. This is great. It lets me read code and get a feel for it quicker. It lets me translate designs between languages and abstractions much easier. And it lets me get stuff done faster.

The downside is that I find it harder to explain to teammates (and worse, management) why a particular design is advantageous; especially teammates that are behind the times on best practices. "This design is more testable!" or "You should favor composition over inheritance." go right over their heads, and lead into the rabbit hole of me trying to clue everyone in to the last decade of software engineering advances.

I'll get better at it with practice of course, but in the mean time it involves a lot of wasted time and/or bad design (that will lead to wasted time fixing it later). How can I better explain why a certain design is superior, when the benefits aren't completely obvious to the audience?


答:
Well, this answer isn't really as specific to programming as you might think.  You have to bring it back to things they do understand.

If it's something like composition over inheritance, you probably just have to say that currently perhaps 90% of developers would consider that a best practice (a wild guess, based partly on the fact that 100% of developers agree on almost nothing), and you agree and would be happy to go into why.

I try to be as honest as I can about what's controversial, and what percentage of developers would agree with me.

This generally works better with management than developers, who probably will make you go down the rabbit hole of explaining whether you are really advocating good design and how do you know it.  There is something commendable in this, but it means you must put a lot of time in.  Unless they trust you enough to take your word for such things, at least provisionally.  On the good side, they may convince you that you are wrong, which beats cold, hard reality convincing you down the road.

For things like a design being more testable, if they don't agree that it is more testable then it's pretty much the same as the first example.  If they don't agree that it's desirable to be more testable, then you have to bring it back to things they understand.  This would most likely be management, and you can talk about lower development costs in the long term, less QA, more predictable processes (since the length of repeated QA cycles is hard to predict), etc.

I think part of the problem is that you underestimate how difficult it is to get a team to agree with you on anything controversial, even if you happen to be correct (and of course you may not be).  Programming is partly a sociological exercise and you may need to schedule time to actually go down some of those rabbit holes, since a great design that no one understands or gets behind is rarely a great design in practice. So don't think of that time as wasted, think of it as a necessary part of your project's success.  Even though it would be so much easier if you could somehow skip it.


问:
Why are exceptions considered better than explicit error testing?

Possible Duplicate:

  Defensive Programming vs Exception Handling?

  if/else statements or exceptions

I often come across heated blog posts where the author uses the argument: "exceptions vs explicit error checking" to advocate his/her preferred language over some other language. The general consensus seems to be that languages that make use of exceptions are inherently better / cleaner than languages which rely heavily on error checking through explicit function calls.

Is the use of exceptions considered better programming practice than explicit error checking, and if so, why?

答:
In my mind, the biggest argument is the difference in what happens when the programmer makes an error.  Forgetting to handle an error is a very common and easy mistake to make.

If you return error codes, it is possible to silently ignore an error.  For example, if malloc fails, it returns NULL and sets the global errno.  So correct code should do

```<code>void* myptr = malloc(1024);
if (myptr == NULL) {
    perror("malloc");
    exit(1);
}
doSomethingWith(myptr);
</code>```

But it is very easy and expedient to instead only write:

```<code>void* myptr = malloc(1024);
doSomethingWith(myptr);
</code>```

which will unexpectedly pass NULL into your other procedure and likely discard the errno which was carefully set.  There is nothing visibly wrong with the code to indicate that this is possible.

In a language that uses exceptions, instead you would write

```<code>MyCoolObject obj = new MyCoolObject();
doSomethingWith(obj);
</code>```

In this (Java) example, the new operator either returns a valid initialized object or throws OutOfMemoryError.  If a programmer must handle this, they can catch it.  In the usual (and conveniently, also the lazy) case where it is a fatal error, the exception propagation terminates the program in a relatively clean and explicit manner.

That is one reason why exceptions, when properly used, can make writing clear and safe code much easier.  This pattern applies to many, many things which can go wrong, not just allocating memory.

Body:
In my mind, the biggest argument is the difference in what happens when the programmer makes an error.  Forgetting to handle an error is a very common and easy mistake to make.

If you return error codes, it is possible to silently ignore an error.  For example, if malloc fails, it returns NULL and sets the global errno.  So correct code should do

void* myptr = malloc(1024);
if (myptr == NULL) {
    perror("malloc");
    exit(1);
}
doSomethingWith(myptr);

But it is very easy and expedient to instead only write:

void* myptr = malloc(1024);
doSomethingWith(myptr);

which will unexpectedly pass NULL into your other procedure and likely discard the errno which was carefully set.  There is nothing visibly wrong with the code to indicate that this is possible.

In a language that uses exceptions, instead you would write

MyCoolObject obj = new MyCoolObject();
doSomethingWith(obj);

In this (Java) example, the new operator either returns a valid initialized object or throws OutOfMemoryError.  If a programmer must handle this, they can catch it.  In the usual (and conveniently, also the lazy) case where it is a fatal error, the exception propagation terminates the program in a relatively clean and explicit manner.

That is one reason why exceptions, when properly used, can make writing clear and safe code much easier.  This pattern applies to many, many things which can go wrong, not just allocating memory.


问:
Is it possible to keep only one Database for both web and desktop applications?
I'm experiencing a trouble with my business model, let me explain better.

I'm developing a software for 1 year and few months, it's for the food industry, more exactly a software to: Delivery, Take Way, Table Reservation, POS, Accounts Payable and Receivable, Prints(receipt), Kitchen Monitors Orders, Customers Orders Control and Fiscal Area.

Well, I had separated the software mainly in two areas, one is web area and the other is desktop area (Used by Admins only) and local installed.

1 - Web Area (Basically do the follow:)

Show Catalog with the products

Customers Make Orders

Customers Pay for the Orders

etc ... as mentioned above

2 - Desktop Area

Manage Orders

Manage Customers

Manage Suppliers

Manage Accounts Payable and Receivable

etc ... as mentioned above

The web area is hosted in an online web server (scripts and database are online). The Desktop area is hosted locally in a Linux machine with a local database and local scripts files.

My question is:
Is it possible to keep only one Database for both applications? If YES, please what is the best approach?

Follow my technical specification environment

Database: Actually I have two databases working and I would love to keep only one.

Operating System: Linux (Kernel 2.6.X and above) or Windows (XP and above)

For the Web Area

Apache, PHP, Python, Java Script, Shell Script and MySQL.

For the Desktop Area:

PHP-GTK2, Apache, PHP, MySQL and Shell Script.

Addtional Information about the system [EDITED]

The main purposes to have a Desktop environment is:

I need to print and give out Tax Coupon on each new order.

I have the drawer.

I have a serial reader (Bar code).

I have a terminal to query for information.

and few other stuffs that is so hard if not impossible to do in the web environment.

Desktop relational schema: 104 tables.
Web relational schema: 42 tables.

Permissions is assigned based on: Deny all by default, and assigns as needed.

(Validation / Sanitization) has already been done in the web application.

Until now performance is not a problem, since every fiscal year part of my database will be archived.
(Also customer, suppliers and all related data about them will be archived after 3 years of inactivity).

My real problem is I have 2 environments today and I would love to have only 1.
Then "merge" the both worlds into one is an option, but not sure about.
I would love to read here a lot of ideas about this matter.

Observation about the process: Today it is in operation and it works fine, but I feel like waste time in some process.

Take a look in the scenario:

The order is made in the internet, then stored in my Web database.

The "order" is sent to the kitchen and prepared.

Print a receipt (Tax Coupon), put it with the order and delivery to the customer.

A Tax Coupon is generated by my Desktop Environment and it need a call to the orders table, but it is not the Web Order Table but a Desktop Order Table.

In few words I need to generate again the order to fill up the Tax Coupon. The same happen to Customer Register, Supplier Register and few other stuffs.

I hope this information turn my question more readable. Thanks Again!

答:
It looks like orders are common to both databases - if so then it makes sense to use the one common database as there is no need to synchronize the two. If there is no commonality in the data, then keep them separate.

A couple of things if you are going to have them together in one database.

1) Create a separate log-on for the web and desktop applications. This will make it easier to debug issues using trace tools. Assign access permissions according to what each user needs to have access to.

2) Build a Data layer and only allow the web site to access to database by calling stored procedures - This will help prevent SQL injection attacks. This could possibly be a shared library between the two.

3) If performance becomes an issue, then you would need to be able to move the lesser used tables to another physical disk (I would suspect the Accounts and suppliers tables) So consider in the design phase if there is the need to have separate schema (Ties in with point 1 with regards to permissions) for transactional and non-transactional tables.


答: It is valid to share the same database between desktop apps and web apps. However, I don't see why you need desktop technology per-se. You have 2 different groups of functions that has different users but that does not call for using a desktop and web-based application environments. There is usually a benefit of hiding your database from the web if you don't have to have it there. However, many accept the risk after implementing the usual security measures, which you need anyway for the web portion of the application. There are several issues with having multiple environments so, with batch processing aside, I don't think you have shown compelling requirements as why the desktop functionality is mandatory in your question, and as a result, I don't see there is a case for 2 different environments, all the functions you have listed can be handled in web environment (except for the batch processing which is not clearly detailed).</p>

Title: Is it possible to keep only one Database for both web and desktop applications?

Body:
I'm experiencing a trouble with my business model, let me explain better.

I'm developing a software for 1 year and few months, it's for the food industry, more exactly a software to: Delivery, Take Way, Table Reservation, POS, Accounts Payable and Receivable, Prints(receipt), Kitchen Monitors Orders, Customers Orders Control and Fiscal Area.

Well, I had separated the software mainly in two areas, one is web area and the other is desktop area (Used by Admins only) and local installed.

1 - Web Area (Basically do the follow:)

Show Catalog with the products

Customers Make Orders

Customers Pay for the Orders

etc ... as mentioned above

2 - Desktop Area

Manage Orders

Manage Customers

Manage Suppliers

Manage Accounts Payable and Receivable

etc ... as mentioned above

The web area is hosted in an online web server (scripts and database are online). The Desktop area is hosted locally in a Linux machine with a local database and local scripts files.

My question is:
Is it possible to keep only one Database for both applications? If YES, please what is the best approach?

Follow my technical specification environment

Database: Actually I have two databases working and I would love to keep only one.

Operating System: Linux (Kernel 2.6.X and above) or Windows (XP and above)

For the Web Area

Apache, PHP, Python, Java Script, Shell Script and MySQL.

For the Desktop Area:

PHP-GTK2, Apache, PHP, MySQL and Shell Script.

Addtional Information about the system [EDITED]

The main purposes to have a Desktop environment is:

I need to print and give out Tax Coupon on each new order.

I have the drawer.

I have a serial reader (Bar code).

I have a terminal to query for information.

and few other stuffs that is so hard if not impossible to do in the web environment.

Desktop relational schema: 104 tables.
Web relational schema: 42 tables.

Permissions is assigned based on: Deny all by default, and assigns as needed.

(Validation / Sanitization) has already been done in the web application.

Until now performance is not a problem, since every fiscal year part of my database will be archived.
(Also customer, suppliers and all related data about them will be archived after 3 years of inactivity).

My real problem is I have 2 environments today and I would love to have only 1.
Then "merge" the both worlds into one is an option, but not sure about.
I would love to read here a lot of ideas about this matter.

Observation about the process: Today it is in operation and it works fine, but I feel like waste time in some process.

Take a look in the scenario:

The order is made in the internet, then stored in my Web database.

The "order" is sent to the kitchen and prepared.

Print a receipt (Tax Coupon), put it with the order and delivery to the customer.

A Tax Coupon is generated by my Desktop Environment and it need a call to the orders table, but it is not the Web Order Table but a Desktop Order Table.

In few words I need to generate again the order to fill up the Tax Coupon. The same happen to Customer Register, Supplier Register and few other stuffs.

I hope this information turn my question more readable. Thanks Again!


答:
If you need to reference a document then I'd look no further than the esteemed "Code Complete."  In it, the book describes how many errors are caught with unit tests vs peer review.  It's astounding.  Unit tests, if memory serves me right, catch only ~30% of all bugs while formal peer reviews catch ~70%.

Take that information, show him in the book and appeal to his financial side.  It takes far longer and is much more expensive to allow bugs through than it is to catch them early.

Title: Tips on persuading boss that code review is a good thing

Body:
Let's say one works in a hypothetical company that has several developers that rarely worked together on projects and the Boss didn't believe that code reviews are worth the time and cost.

What are various arguments that could be presented in this scenario that will portray the benefit of code review?  Furthermore, what are the potential arguments against code review here and how can these be countered?


答:
Let's put the implementation problems of many languages aside. The benefit exceptions have is that they can be centralized to handle all kinds(in theory) of exceptional states of the program. The problem they tackle is that exceptional things happen and can hardly ever be predicted. What is great(in theory) with exceptions is that you are safe as long as you:

Write exception safe code to highest degree possible

Catch the exceptional states via exceptions

Handle the exceptions accordingly

Title: Why are exceptions considered better than explicit error testing?

Body:
Possible Duplicate:

  Defensive Programming vs Exception Handling?

  if/else statements or exceptions

I often come across heated blog posts where the author uses the argument: "exceptions vs explicit error checking" to advocate his/her preferred language over some other language. The general consensus seems to be that languages that make use of exceptions are inherently better / cleaner than languages which rely heavily on error checking through explicit function calls.

Is the use of exceptions considered better programming practice than explicit error checking, and if so, why?


答:
While Steven's answer provides a good explanation, there is another point which I find is rather important. Sometimes when you check an error code, you cannot handle the failure case immediately. You have to propagate the error explicitly through the call stack. When you refactor a big function, you may have to add all the error-checking boilerplate code to your sub function.

With exceptions, you only have to take care of your main flow. If a piece of code throws some InvalidOperationError, you can still move that code to a sub function and the error management logic will be maintained.

So exceptions allows you to refactor faster and to avoid boiler plate.


答:
Easy to forget exit codes

Duplicate code. Checking the error code and returning the error code when there is an error would cause lots of duplicate code to handle and lots to change if the return type changes. Also what to do when different types can cause an error?

Exceptions are ran outside of the code path which means there is no work checking the return value. But there is work in the binary somewhere when the exception code is ran.

Easy to see what functions handles what type of errors. You dont have to look through a lot of code, just scroll through catch.

More details (in certain languages). It has built in information such as what line, function, etc. Putting that into a error class would be tedious. Likely you would only write function name and hopefully the type or cause of the error.

Debuggers understand exceptions are errors and may pause when it hits one while you are debugging. Tools help :)


问:
bug: deviation from requirements vs deviation from expectations
I am not clear on this one. No matter the terminology, in the end the software fault/bug causes (according to a lot of sources):

Deviation from requirements

   Devation from expectations

But if the expectations are not in requirements, then stakeholder could see a bug everywhere as he expected it to be like this or that..So how can I really know? I did read that specification can miss things and then of course its expected but not specified (by mistake).

答:
Requirement is the interface between expectation and developed product: Expectation --> Requirement --> Product

if a product deviate from expectation, actually, it includes two condition.

Deviation between requirement and product: it is a obvious 'bug'.

Deviation between requirement and expectation: how to define whether it is a bug?
I prefer to the answer of MainMa: the requirement is often incomplete, so if most people would have the same expectation for the same product, then you may want to implement the expectation, even if it is not defined in requirement.

I add one case: The expectation was lost when it was transferred to requirement. These bugs are defined as a bug from analysis or a system level bug.


问:
Where can I locate business data to use in my application?
This question talks about any and all free public raw data which appeared to have valuable pieces but nothing that really provides what I am looking for.

Instead of using a socially defined listing of businesses (foursquare), I would like a business listing data set of registered businesses and associated addresses that could then be searchable based on location (coordinates). The critical need is that the data set should be filterable based on varying criteria (give me all restaurants, coffee shops, etc...).

If the data is free that is great but anywhere that sells this type of data would also suffice. Infochimps looked like a possibility but perhaps something a bit more extensive exists.

Where can I find a free or for fee data set of registered business that is filterable based on type of business and location?

答:
There are a number of places to collect about businesses and their locations:

Township, County, State Chamber of Commerce.  I have actually collected a lot business data from such places.  You might have to join, but you do get access to the data.

I have never investigated whether the federal government offers business specific info.  But you might want to give it a try -- the government provides data about all sorts of weird stuff.


问:
Where to place the R code for R+Sweave+LaTeX workflow
I spent the last week learning 3 new tools: R, Sweave, and LaTeX. One question that came to my mind when working through my first project: Where do I place the majority of the R code?

The tutorials that I read online placed the majority of the R code in the LaTeX .Rnw file. However, I find having a bunch of R calculations in the LaTeX file distracting. What I do find extremely helpful (of course) is to call out to R code in the LaTeX file and embed the result.

So the workflow I've been using is to place 99% of my R code in my .R file. I run that file first, save a bunch of calculations as objects, and output the .Rout file once finished (to save the work). Then when running Sweave, I load up that .Rout file, so that I have the majority of my calculations already completed and in the Sweave R session.

Then my LaTeX callouts to R are quite simple: Just give me the XTable stored in 'res.table', or give me the result of an already-computed calculation stored in the variable 'res'.

So I push towards the minimal amount of R code in the LaTex file possible, to achieve the desired result (embedding stats results in the LaTeX writeup).

Does anyone have any experience with this approach? I'm just worried I might run into trouble further down the line, when I start really trying to load up and leverage this workflow.

答: I have the same obsession of keeping the code out, but I use knitr, which builds on Sweave. It might solve your issue if the issue is to avoid the .Rout file.


答:
I'd like to think of exceptions as...

They allow you to write code the way it naturally tends to be written

When writing code, there's a number of things that the human brain needs to juggle:

What is the logic I am trying to express here?

How do I actually accomplish this in language XXXX?

How does this code fit into the rest of the application?

Why do I keep getting these build errors?

Am I forgetting about boundary conditions?

Is this code readable and maintainable enough?

What happens if something in this code fails?

Am I producing code in consistent style and use the right coding conventions?

Each one of these bullets requires a certain amount of concentration and concentration is a limited resource. This is why people who are new to a project will often forget things towards the bottom of the list. They are not bad people, but because so many things may be new to them (language, project, weird errors, etc...), they simply do not have the capacity to deal with other bullets.

I've done my share of code reviews and this trend is very apparent. A person with less experience will forget more things. These things include style and often enough error handling. When people are having a hard time getting the code to work, error handling tends to be in the back of their minds. Sometimes they'll go back and add some if-statements here and there, but rest assured, they will forget a whole bunch of things.

Exception handling allows you to write code where the meat of your logic is written as though there are no errors. You make a function call and the next line can simply assume the previous line succeeded. This has an added bonus of producing code that is much easier to read. Have you ever seen an API reference with code examples that had a comment, "// Error handling omitted for clarity"?  If they remove error handling in documentation to make the example easier to read, wouldn't it be great if you could do the same thing in production code and make that easier to read as well? That's exactly what exceptions let you do.

Now at least one person reading this post will say, "pffttt some noob doesn't know how to code. I never forget error handling." a) Good for you, but more importantly b) as I said above, coding requires your brain to concentrate and there's only so much brain to go around; that applies to EVERYONE. If your code is easy to read, that's less concentration.  If you can put try/catch around a large chunk and then simply code application logic, that's less concentration.  Now you can use that extra capacity for more important things, like getting the actual job done that much faster.


问:
How to have a maintainable and manageable Javascript code base
I am starting a new job soon as a frontend developer. The App I would be working on is 100% Javascript on the client side. all the server returns is an index page that loads all the Javascript files needed by the app.

Now here is the problem:

The whole of the application is built around having functions wrapped to different namespaces. And from what I see, a simple function like rendering the HTML of a page can be accomplished by having a call to 2 or more functions across different namespace...

My initial thought was "this does not feel like the perfect solution" and I can just envisage a lot of issues with maintaining the code and extending it down the line.

Now I would soon start working on taking the project forward and would like to have suggestions on good case practices when it comes to writing and managing a relatively large amount of javascript code.

答:
I would recommend to look at JavaScript module management and compression, also called Steal JS which is part of the great JavaScript MVC framework. This could be generally interesting for larger JS applications. It can load module files dynamically during development and for production you can create one compressed JavaScript file (it can do CSS, too).

Another alternative to look is RequireJS. however, I did not explore it in depth. just keep that option in mind.


答:
Short Answer: You would definitely have less headaches with a single database.

Otherwise, you may end-up with record synchronization issues, as well as with record duplicates, in all local databases that you might use.

What would you need is just to create a DAL (data access layer) and make your client applications (desktop, wen, mobile, etc) access your database through your DAL.


答:
I don't really have a solution to your question but some time ago I've faced exactly the same dilemma and was looking to answer exactly this same question.

I would find myself on one side of the argument and someone else on the other side and even though every fiber of my body told me the right design is X, I could not back it using words.

Worse yet is that sometimes I would concede the point and let the other person implement it their way only to have their design blow up in my face and then I'd think, "Yeah, this is perfect example of why I didn't want to do it that way. If only I could demonstrate this code to them back then."

Well, I never really found the answer but few days ago as I was flipping through Lean Software Development: An Agile Toolkit, I came across something interesting that might suggest that the answer doesn't actually exist.  A section of the book was talking about leaders in other fields, especially in emergency response units and how those leaders made decisions. When there's a fire, or someone is shooting at you, those leaders never sit down and argue pros/cons with their teammates. Instead, they use intuition, which was developed through training and experience to help them make decisions. Same applies to our profession: how can you make fully logical decision when faced with a ton of unknowns and variability that is so common in software development?  The authors argue that instead of attempting to justify every decisions, developers should be encouraged to train and improve their instincts so eventually they would "just know" what to do.

The only way I found to get past these arguments is to build a proven track record of my work. To show management and others on my team that the design decisions I make in my code result in code that is easier to maintain, extend and is more reliable.  You do this repeatedly and people will notice you. At that point, your opinion, which might only be based on your instinct, will have a much higher weight than it does today.  This strategy worked with 90%+ of my team including my boss. Unfortunately, you might find one or two guys who are completely stubborn and will refuse to see anything your way. At that point, you have few options:

You can try to pull rank (I ended up going to my boss and asking for a rank because I was so tired of these dead-end arguments)

You can try to lobby for majority of the team to support you.

If the project can afford (i.e not too much loss in productivity), what in your opinion is a bad decision, let the other person win the argument.  One of two things will happen:

In some cases (hopefully very small portion), your intuition will be wrong and you will end up learning something.  Good for you.

In most cases (again... hopefully), you AND the person who was advocating "bad" design will realize exactly why it is bad; after all hindsight is always 20/20. Hopefully, this will be a lesson to that person that possibly you know what you are talking about and next time they'll think twice arguing their case.


答:
How productive will you be if you go blind from staring at the monitor for too long or have a mental breakdown from working nonstop?  Personally, I'd worry more about actually going blind or having a breakdown, but it sounds like you're more worried about the productivity standpoint.

Now to be fair, a 5 minute break every 30 minutes sounds a bit on the excessive side.  But I don't recommend skipping out on breaks because it makes you less productive in the short term.

Title: Is taking frequent breaks really that beneficial when programming?

Body:
I keep reading that it is recommended for a programmer to take frequent breaks while programming, and the usual recommendation I see is 5 minutes every half hour or 10 minutes every hour.

I gave it a try, but quite often I find something interesting during those 5 minutes, and it takes me away from what I was working on for longer than I planned. Either that, or my mind gets focused on something else and I find it hard to get back into my work and don't focus very well.

Is it really that beneficial to take frequent breaks while programming? Am I doing something wrong for it to be decreasing my productivity instead of increasing it?


答:
The fundamental difference for me is reading vs. writing:

Error code handling tends to clutter the intent: exception-based code is usually easier to read since the source focuses on the things that should happen, rather than what might.

OTOH, A lot of exception-based code is harder to write, because for a correctness analysis you have to argue about "unrelated" details, such as construction / destruction order, partially constructed objects, garbage collection etc.

How hard? This hard.

Generating meaningful exceptions can clutter the source as well, I have code bases where virtually every lines of code is followed by two or three lines building a literate exception.

For transferring meaningful exceptions to the top-level, they often need to be repackaged. When I click "rebicker cells", an error message like "Sharing violation on %tmp%\foo\file536821" isn't much more helpful than "Error 77".

I really don't have a preference, both options are equally ugly. What's worse: which one is better seems to depend a lot on the project, in hard-to-predict ways. In my experience, low-level hardware interaction is smoother with error codes (might be the clients...), low level data access is better with exceptions.


问:
Style bits vs. Separate bool's
My main platform (WinAPI) still heavily uses bits for control styles etc. (example).

When introducing custom controls, I'm permanently wondering whether to follow that style or rather use individual bool's. Let's pit them against each other:

```<code>enum EMyCtrlStyles
{
   mcsUseFileIcon = 1,
   mcsTruncateFileName = 2,
   mcsUseShellContextMenu = 4,
};

void SetStyle(DWORD mcsStyle);
void ModifyStyle(DWORD mcsRemove, DWORD mcsAdd);
DWORD GetStyle() const;

...
ctrl.SetStyle(mcsUseFileIcon | mcsUseShellContextMenu);
</code>```

vs.

```<code>CMyCtrl & SetUseFileIcon(bool enable = true);
bool GetUseFileIcon() const;

CMyCtrl & SetTruncteFileName(bool enable = true);
bool GetTruncteFileName() const;

CMyCtrl & SetUseShellContextMenu(bool enable = true);
bool GetUseShellContextMenu() const;

ctrl.SetUseFileIcon().SetUseShellContextMenu();
</code>```

As I see it,

Pro Style Bits

Consistent with platform

less library code (without gaining complexity), less places to modify for adding a new style

less caller code (without losing notable readability)

easier to use in some scenarios (e.g. remembering / transferring settings)

Binary API remains stable if new style bits are introduced

Now, the first and the last are minor in most cases.

Pro Individual booleans

Intellisense and refactoring tools reduce the "less typing" effort

Single Purpose Entities

more literate code (as in "flows more like a sentence")

No change of paradim for non-bool properties

These sound more modern, but also "soft" advantages. I must admit the "platform consistency" is much more enticing than I could justify, the less code without losing much quality is a nice bonus.

1. What do you prefer? Subjectively, for writing the library, or for writing client code?

2. Any (semi-) objective statements, studies, etc.?

答:
I prefer using enum bitflags in both library and client code for a collection of boolean options that can be toggled independently. It's an idiom I'm familiar with, and allows me to save the configuration in a single int and pass it around without having to define a new struct or class to contain all the flags. It also cuts down on typing without really sacrificing clarity.

Objectively, a struct containing bools would be more type-safe in C++, as discussed in this SO question. Irrelevant if you're using plain C.

Title: Style bits vs. Separate bool's


问:
What technologies are needed to be a freelance web developer / designer targeting small businesses?
First off, I'm not looking for this answer: "learn PHP/MySQL, JQuery, HTML/CSS...."

My background, I wear many hats, and do many things. Currently I manage investment accounts with a business partner who is also a friend. He happens to be attending business / law school perusing a joint JD and MBA. As a result, we're putting our into "coast", maintaining our current clients, but not acquiring more.

Recently I've picked up some freelance graphic design / web development / online marketing side work (Photoshop, HTML/CSS, WordPress) through some personal networks. The work is enjoyable; now I'm thinking about expanding it into a larger business with these primary goals:

augment my finances (I'm shooting for about $1,000-2,000 per mo.),

learn new technologies,

involve myself with meaningful work.

As an entrepreneur I don't mind the aspects of running a business that hassle other freelancers...

-- the marketing

-- the billing

-- etc.

I'm considering targeting the small to middle market businesses and organizations where I can contribute in marketing, design, and development building projects from the ground up. Thus I'll have freedom to decide the specific technology (I won't have to work with an existing code base).

What kinds of projects should I focus on? What technologies are a good fit for this style of work?

For example: It might be fun to develop with Ruby on Rails. However, maybe a lot of projects would be rolling out e-commerce solutions. Thus, I should focus on PHP due to more shopping cart options, skipping ROR entirely.

答:
I am also suggesting you to learn Magento CMS. Like Clutch sad, wordpress and drupal are way easy to learn and you are going to paid at very low prices.

Learn Magento and target Turkey like countries which are developing their online sale market. ( This is way easy then you thought. Just add them on Linkedin :) )

After that, $1,000-2,000 per mo. is just a piece of cake.


问:
How should I implement Transaction database EJB 3.0
In the CustomerTransactions entity, I have the following field to record what the customer bought:

```<code>@ManyToMany
private List<Item> listOfItemsBought;
</code>```

When I think more about this field, there's a chance it may not work because merchants are allowed to change item's information (e.g. price, discount, etc...). Hence, this field will not be able to record what the customer actually bought when the transaction occurred.

At the moment, I can only think of 2 ways to make it work.

I will record the transaction details into a String field. I feel that this way would be messy if I need to extract some information about the transaction later on.

Whenever the merchant changes an item's information, I will not update directly to that item's fields. Instead, I will create another new item with all the new information and keep the old item untouched. I feel that this way is better because I can easily extract information about the transaction later on. However, the bad side is that my Item table may contain a lot of rows.

I'd be very grateful if someone could give me an advice on how I should tackle this problem.

UPDATE: I'd like to add more information about the current design.

```<code>public class Customer implements Serializable {
    @OneToMany
    private List<CustomerTransactions> listOfTransactions;
}

public class CustomerTransactions implements Serializable {
    @ManyToMany
    private List<Item> listOfItemsBought;
}

public class Merchant implements Serializable {
    @OneToMany
    private List<Item> listOfSellingItems;
}
</code>```

答:
One solution would be to add another level of item classification here. Say, GenericItem.

e.g. GenericItem: Shoe

Related items: Running shoe, Walking Shoe, Discounted running shoe, etc.

You can have the merchant select the generic cateogory when adding new items.

You can add more levels depending on the granularity desired for the relation between the customer and the items purchased. You can have a SubItem.

e.g. GenericItem: Shoe

SubItems: Running shoe, Walking Shoe, etc.

Items (for running shoe): discounted, black, etc.

You can factor in the following while making the architectural
decisions:

Complexity: how much complexity in terms of item classification do you want and that you want to expose to the users (merchants)

Performance: more complexity is going to add to performance

Domain: do you anticipate the number and type of items to go very high? in that case, you want a good item classification scheme.

Normalization: apply it to your databse design to see how best you can represent and what you want.

OwnerDisplayName: JamesBoyZ


答:
Actually, I don't believe that "consistency with platform" is a "minor" point in most cases. Quite to the contrary, you should design a library like others are likely to expect to use it. If the primary target audience for, or platform that is targetted by, your library uses bitfields, then you are probably better off using bitfields.

That said, bitfields do have their fair share of disadvantages. They debuted when memory constraints were a very real concern; if you're trying to squeeze something useful into a few dozen kilobytes of RAM or even less, then every byte counts. Consider that the Windows API goes back to the early 1980s, with Windows 1.0 released in 1985 and requiring a whopping 256 KB of RAM and either two floppy disk drives or a single hard drive. This is much less of a concern today now that pretty much all and sundry have several gigabytes of RAM available for server or desktop applications, as well as essentially unlimited, comparatively extremely fast swap space (I don't think Windows 1.0 ever did swapping at all, although I'm pretty sure it did memory page purging), plus JIT compilers, optimizers etc.

Bitfields are opaque; it's much easier to say if (frob.isFrobnicated() && frob.isGlobbified()) than if (frob.getState() & (FROB_FROBNICATED | FROB_GLOBBIFIED) == (FROB_FROBNICATED | FROB_GLOBBIFIED)), let alone when you are looking at the object in a debugger and see that frob.state == 0x27a and trying to figure out what that value means.

One big upside of using separate state variables and accessor/mutator functions is that it is much easier to enforce invariants between related states. For example, if state A has no special requirements, but state B requires that one of but not both of states C and D are set, this is trivial to enforce at compile time if you are using separate state mutator functions, but not quite so obvious when using bitfields.

I work primarily with .NET and Java, both of which frown at bitfields for exposed state in library routines. (There are exceptions, but they are rare.) C is almost certainly different even these days, and I imagine C++ kind of bridges the gap.

Bit fields have one huge advantage: they are atomic. If you access frob.state, you can examine the value safe in the knowledge that it cannot change between comparisons within the same statement (like for example in the if examples above). In a multithreaded application, if you are unlucky, the state of the frob might change between the two calls to isFrobnicated() and isGlobbified(). However, I would think that if this is a major source of bugs, then you have other issues that you need to deal with (like thread-common global state being modified while being used).

Bottom line: you certainly can use bit fields internally if you feel comfortable with them, but for exposed state, I would go with separate values unless there are specific reasons (such as platform usage expectations) for doing otherwise, and you are willing to live with the downsides of that choice. And even then, you may want to consider doing it as an alternative rather than as the only available approach.

Title: Style bits vs. Separate bool's

Body:
My main platform (WinAPI) still heavily uses bits for control styles etc. (example).

When introducing custom controls, I'm permanently wondering whether to follow that style or rather use individual bool's. Let's pit them against each other:

```<code>enum EMyCtrlStyles
{
   mcsUseFileIcon = 1,
   mcsTruncateFileName = 2,
   mcsUseShellContextMenu = 4,
};

void SetStyle(DWORD mcsStyle);
void ModifyStyle(DWORD mcsRemove, DWORD mcsAdd);
DWORD GetStyle() const;

...
ctrl.SetStyle(mcsUseFileIcon | mcsUseShellContextMenu);
</code>```

vs.

```<code>CMyCtrl & SetUseFileIcon(bool enable = true);
bool GetUseFileIcon() const;

CMyCtrl & SetTruncteFileName(bool enable = true);
bool GetTruncteFileName() const;

CMyCtrl & SetUseShellContextMenu(bool enable = true);
bool GetUseShellContextMenu() const;

ctrl.SetUseFileIcon().SetUseShellContextMenu();
</code>```

As I see it,

Pro Style Bits

Consistent with platform

less library code (without gaining complexity), less places to modify for adding a new style

less caller code (without losing notable readability)

easier to use in some scenarios (e.g. remembering / transferring settings)

Binary API remains stable if new style bits are introduced

Now, the first and the last are minor in most cases.

Pro Individual booleans

Intellisense and refactoring tools reduce the "less typing" effort

Single Purpose Entities

more literate code (as in "flows more like a sentence")

No change of paradim for non-bool properties

These sound more modern, but also "soft" advantages. I must admit the "platform consistency" is much more enticing than I could justify, the less code without losing much quality is a nice bonus.

1. What do you prefer? Subjectively, for writing the library, or for writing client code?

2. Any (semi-) objective statements, studies, etc.?


答:
A point of view from a different angle: Error handling is all about security. An unchecked error breaks all assumptions and preconditions the following code was based on. This may open a lot of external attack vectors: From a simple DoS over unauthorized data access to data corruption and complete system infiltration.

Sure, it depends on the specific application, but when assumptions and preconditions are broken, then all bets are off. Within a complex software, you simply can't say anymore with certainty what is possible from then on, and what can and can't be used from extern.

Given that, there is a fundamental observation: When security is treated as an optional add-on that can be attached later, then it fails most often. It works best when it was already considered in the very first basic design stages and built-in right from the start.

This is what you basically get with exceptions: An already built-in error handling infrastructure that is active even if you don't care. With explicit testing, you have to build it yourself. You have to build it as a very first step. Just beginning to write functions that return error codes, without thinking about the big picture until you're in the final stages of your application development, is effectively an add-on error handling, doomed to fail.

Not that a built-in system helps in any way. Most programmers don't know how to do error handling. It's just too complex most of the time.

There are so many errors that can happen, and each error requires its own handling and its own actions and reactions.

Even the same error can require different actions, based on context. What about a File Not Found or an Out Of Memory?

FNF - A third party library needed for your app to run? Terminate.

FNF - The start-up config file of your application? Start with default settings.

FNF - A data file on a network share the user wants your app to open? Disappearing files can happen anytime, even in the microseconds between Exists() and Open(). It's not even an "Exception" in the literal meaning of the word.

OOM - For a 2GB allocation? No surprise.

OOM - For a 100 byte allocation? You're in serious trouble.

Error handling leaks through all your carefully separated abstraction layers. An error in the lowest level may require to notify the user with a GUI message. It may require a decision from the user for what to do now. It may need logging. It may need recovery operations in another part, e.g. open database or network connections. Etc.

What about state? When you call a method on an object that invokes state changes and it throws an error:

Is the object in an inconsistent state and needs a rebuild?

Is the object state consistent but (partially) changed and needs an additional rollback or a rebuild?

Is a rollback done within the object and it remains unchanged to the caller?

Where is it even sensible to do what?

Just show me one learner's book where error handling is rigorously designed from the start and consequently used through all the examples, without being left out for brevity and readability and as excercise for the reader. If this is applicable from an educational POV is another question, but it's no surprise that error handling is often enough a second or third thought when it should be the very first.


答:
If both are implemented perfectly the differences are not that much, however, usually nothing is perfect. If the handling of some errors is missing, in case of exceptions the program halts with a visible error, while the program with error testing just keeps running with undefined behavior.

If you develop a program and have an error you did not notice, what would you rather have?

The program crashes so you start looking for and find the bug (or the program crashes at the beta testers, or maybe at the user so they can send in a bug report) (exception handling)

The program keeps running, meanwhile silently corrupting some variables without causing any visible effects on your computer. However, it will delete all the users data when they run it, without them noticing when it happens. (error testing)


问:
Replacing out parameters with struct
I'm encountering a lot of methods in my project that have a bunch of out parameters embedded in them and its making it cumbersome to call the methods as I have to start declaring the variables before calling the methods.

As such, I would like to refactor the code to return a struct instead and was wondering if this is a good idea.

One of the examples from an interface:

```<code>void CalculateFinancialReturnTotals(FinancialReturn fr, out decimal expenses, out decimal revenue, out decimal levyA, out decimal levyB, out decimal profit, out decimal turnover, out string message)
</code>```

and if I was to refactor that, i would be putting all the out parameters in the struct such that the method signature is much simpler as below.

```<code>[structName] CalculateFinancialReturnTotals(FinancialReturn fr);
</code>```

Please advise.

答:
This is pretty much a non-question to me. Yes, what you suggest is most likely an improvement over the current design.

The overall best approach is dependent on the context though and without knowing the broader context - just that isolated example - one cannot recommend much beyond what you have already thought of.

For example, what other methods are there? Do they have some common denominator (I mean similar set of out parameters); can you reuse this struct (good) or would you have to create many different structs (bad)?

And why a struct, not a class? Remember that structs can't be inherited.

The name of this method - CalculateFinancialReturnTotals - is a code smell in its own right to me. My feel is that CalculateTotals should be sufficient. If it's not obvious that it deals with financial returns, the overall design might be flawed somehow. But it's just guessing.

Title: Replacing out parameters with struct


答:
Exception-based code moves the error handling out of the main program flow. Instead the error handling is moved to either object destructor or to the catch construct.

The biggest advantage and also the biggest drawback with exception is that it does not force you to think about error handling. With exception, you often would just write straightforward code and let the the destructor does its job, and forgot about that one little scenario that the destructor does not handle and need to be done manually (which is clearly documented and therefore it's totally your own fault for forgetting). The same scenario could happen with error code, but when writing code with error code, you are forced to check the manual/documentation/source all the time and it is less likely you'll forget about that one little condition.

Yes, this mean exceptions might sometimes make it harder to write correct code.

Writing a bad code with error code is easy, writing a good code with error code is hard. Writing a decent code in exception is easy (because any errors terminates the program or is caught by a very high level handlers that could warn of the impending doom, instead of being passed around silently), writing good code with exception is really hard (because you're handling the errors an arms away from the place where the error happens).


问:
Futures/Monads vs Events
In an application framework
when performance impact can be ignored (10-20 events per second at max),

what is more maintainable and flexible to use as a preferred medium for communication between modules - Events or Futures/Promises/Monads?

It's often being said, that Events (pub/sub, mediator) allow loose-coupling and thus - more maintainable app... My experience deny this: once you have more that 20+ events - debugging becomes hard, and so is refactoring - because it is very hard to see:  who, when and why uses what.

Promises (I'm coding in Javascript) are much uglier and dumber, than Events. But: you can clearly see connections between function calls, so application logic becomes more straight-forward. What I'm afraid. though, is that Promises will bring more hard-coupling with them...

p.s: the answer does not have to be based on JS, experience from other functional languages is much welcome.

答:
Monads and events play quite nicely together, for example have a look at .NET Rx. I think there should be even an JavaScript implementation.
http://msdn.microsoft.com/en-us/data/gg577609.aspx</p>

Title: Futures/Monads vs Events


问:
Bug Tracking Etiquette - Necromancy or Duplicate?
I came across a really old (2+ years) feature request issue in a bug tracker for an open source project that was marked as "resolved (won't fix)" due to the lack of tools required to make the requested enhancement. In the time elapsed since that determination was made, new tools have been developed that would allow it to be resolved, and I'd like to bring that to the attention of the community for that application.

However, I'm not sure as to what the generally accepted etiquette is for bug tracking in cases like this. Obviously, if the system explicitly states to not duplicate and will actively mark new items as duplicates (much in the way the SE sites do), then the answer would be to follow what the system says. But what about when the system doesn't explicitly say that, or a new user can't easily find a place that says with the system's preference is? Is it generally considered better to err on the side of duplication or necromancy? Does this differ depending on whether it's a bug or a feature request?

答:
As a programmer, I think that information duplicating is generally a bad thing and should be avoided whenever possible. Imagine a table "Issues" in bug-tracker database. Each record in this table should represent an unique issue. When you add second record for the same bug, it actually starts to represent not a bug itself, but the fact that some user discovered it and posted on some date and time. What actually happened is that you posted some additional info about existing issue. This info should be stored in different place, like "IssueComments" table or something like that.

From my point of view, necromancy is less evil. If necromancy is a problem, we should fight with something that causing a problem , not with necromancy itself (if you found some new info about old bug, what's wrong with that? It's totally natural). For example, if someone posts comment on old closed bug, this should somehow capture attention of all interested users.


答:
I would suggest rolling some kind of CMS. With my personal taste, I'd suggest rolling your own as I don't like presenting 3rd party solutions to clients, but that's up to you entirely. If you begin to move down this route, you can cut down your work substantially. All you really have to do with that kind of work is skin the CMS to the clients needs.

I would also start learning how to do some kind of server administration work. Nothing intense, but enough to get a traditional hosting stack off the ground. That way you can offer clients hosting for their projects for additional income.

BTW just a quick note: RoR is a good option for freelancing. You can find plenty of ecommerce/CMS solutions for the framework.

Title: What technologies are needed to be a freelance web developer / designer targeting small businesses?

Body:
First off, I'm not looking for this answer: "learn PHP/MySQL, JQuery, HTML/CSS...."

My background, I wear many hats, and do many things. Currently I manage investment accounts with a business partner who is also a friend. He happens to be attending business / law school perusing a joint JD and MBA. As a result, we're putting our into "coast", maintaining our current clients, but not acquiring more.

Recently I've picked up some freelance graphic design / web development / online marketing side work (Photoshop, HTML/CSS, WordPress) through some personal networks. The work is enjoyable; now I'm thinking about expanding it into a larger business with these primary goals:

augment my finances (I'm shooting for about $1,000-2,000 per mo.),

learn new technologies,

involve myself with meaningful work.

As an entrepreneur I don't mind the aspects of running a business that hassle other freelancers...

-- the marketing

-- the billing

-- etc.

I'm considering targeting the small to middle market businesses and organizations where I can contribute in marketing, design, and development building projects from the ground up. Thus I'll have freedom to decide the specific technology (I won't have to work with an existing code base).

What kinds of projects should I focus on? What technologies are a good fit for this style of work?

For example: It might be fun to develop with Ruby on Rails. However, maybe a lot of projects would be rolling out e-commerce solutions. Thus, I should focus on PHP due to more shopping cart options, skipping ROR entirely.


问:
Shortest Common Superstring: find shortest string that contains all given string fragments
Given some string fragments, I would like to find the shortest possible single string ("output string") that contains all the fragments. Fragments can overlap each other in the output string.

Example:

For the string fragments:

```<code>BCDA
AGF
ABC
</code>```

The following output string contains all fragments, and was made by naive appending:

```<code>BCDAAGFABC
</code>```

However this output string is better (shorter), as it employs overlaps:

```<code>ABCDAGF
^
ABC
 ^
 BCDA
    ^
    AGF
</code>```

I'm looking for algorithms for this problem. It's not absolutely important to find the strictly shortest output string, but the shorter the better. I'm looking for an algorithm better than the obvious naive one that would try appending all permutations of the input fragments and removing overlaps (which would appear to be NP-Complete).

I've started work on a solution and it's proving quite interesting; I'd like to see what other people might come up with. I'll add my work-in-progress to this question in a while.

答:
What you're asking about is the Shortest Common Superstring problem, for which there is no algorithm that works for all cases. But it is a common problem (in compression and DNA sequencing) and several approximation algorithms are well-known.

"Greedy" algorithms are generally accepted to be the most effective (as in, they have the least-bad worst-case).

Have a read of the paper Approximation Algorithms for the Shortest Common Superstring Problem by Jonathan Turner for much more information.


问:
Designing Algorithm Flowchart Application
I need to develop an GUI application in C# where users can freely add conditional/statement blocks on the algorithm flowchart like the one shown below. By freely, I mean users can add a block on wherever the arrows are.

I'm having some problems brainstorming how to approach this problem, especially what to choose for my datastructure to store the blocks. I was thinking LinkedList since everything follows a linear fashion and every node always has a head and tail, but the If/Else block (b>a) has two branches (heads) to store, so this complicates things a little bit.

How would a smart one approach problems like this? My apologies if this question isn't suited for Programmers stackexchange, but this is more of a conceptual problem rather than implementation problem so I figured this place was appropriate for the question.

答: I'd use a graph data structure. They are often implemented using adjacency matrices or adjacency lists. The MSDN has a pretty solid tutorial. The article covers both of the aforementioned structures.</p>


问:
Case insensitive keywords in a language
We're trying to write a custom scripting language. There has been a suggestion to make the language forgiving by providing case insensitive keywords.

I personally do not like the idea, but there are few people in my team leaning towards it, saying it will make the end user happy! Examples of languages like FORTRAN, BASIC, SQL are given saying that these are case insensitive.

Is this a good idea?

答:
From my personal experience I don't see a big difference between case sensitive and insensitive languages.

More important thing is naming and structural conventions that a programmer should keep in his code and no compiler or parser checks it for him. If you stick to some kind of rules you will easily know a proper name (you won't think if you named a variable checkOut or CheckOut) and your code probably will be case sensitive and easier to read.

One shouldn't use CheckOut and checkOut and checkout and cHeCkOuT and CHECKOUT in the same meaning. It will hurt readibility and make understanding that kind of code more painfull (but there are worse thing that one can do to destroy readibility of code).

If you use some kind of rules you will see at glance for example:

CheckOut.getInstance() - it's static method of a class called
checkOut.calculate() - it's a method of an object kept in variable or public field called
_checkOut.calculate() - it's a method of an object kept in private field called
CHECKOUT - it's a final static or constant field / variable

without checking out some other files or parts of a file. It makes reading code faster.

I see pretty many developers using similar rules - in languages which I often use: Java, PHP, Action Script, JavaScript, C++.

In a rare case one might be angry on case insensitiveness - for example when wanted to use CheckOut for a class name and checkOut for a variable and cannot because it collides with each other. But it's a problem of a programmer that is used to case sensitivity and to using it in his naming conventions. One can have rules with standard prefixes or postfixes in a case insensitive language (I don't program in VB but I know that many VB programmers have this kind of naming conventions).

In few words: I see case sensitiveness better (only for object oriented languages) because most of developers use case sensitive languages and most of them use naming conventions based on case sensitivity so they would like better a language to be case sensitive so they would be able to stick to their rules without some sort of modifications. But it's rather religious argument - not an objective one (not based on real drawbacks or good sides of case sensitiveness - because I don't see any when it comes to a good developer, when it comes to a bAd DeVeLoPeR one could produce nightmare code even when there is case sensitiveness so it's not a big difference).

Title: Case insensitive keywords in a language


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
If the IDE has code formatting available I do not use braces.

On the other hand, where code may be edited in other editors which does not support auto formatting it is dangerous not to put braces as mentioned in other posts. But even so I prefer not to use braces, and it has not been problem for me.


问:
Serializing network messages
I am writing a network wrapper around boost::asio and was wondering what is a good and simple way to serialize my messages. I have a message factory which can take care of dispatching the data to the correct builder, but I want to know if there are any established solutions for getting the binary data on the sender side and consequently passing the data for deserialization on the receiver end.

Some options I've explored are: passing a pointer to a char[] to the serialize/deserialize functions (for serialize to write to, and deserialize to read from), but it's difficult to enforce buffer size this way; building on that, I decided to have the serialize function return a boost::asio::mutable_buffer, however ownership of the memory gets blurred between multiple classes, as the network wrapper needs to clean up the memory allocated by the message builder.

I have also seen solutions involving streambuf's and stringstream's, but manipulating binary data in terms of its string representation is something I want to avoid. Is there some sort of binary stream I can use instead? What I am looking for is a solution (preferrably using boost libs) that lets the message builder dictate the amount of memory allocated during serialization and what that would look like in terms of passing the data around between the wrapper and message factory/message builders.

PS. Messages contain almost exclusively built-in types and PODs and form a shallow but wide hierarchy for the sake of going through a factory.

Note: a link to examples of using boost::serialization for something like this would be appreciated as I'm having difficulties figuring out the relation between it and buffers.

答:
Since you can't have your cake and eat it (see comment thread for the question), I've decided on the following solution:

The network wrapper will keep a boost::asio::streambuf, while serialization/deserialization will happen over ostream/istream. This way the message builders don't have to deal with memory management, can use as much/as little as they need and can choose whether they want to serialize as binary or text. As an added benefit, I can also easily serialize messages to/deserialize from a file for record/replay during debugging.

Title: Serializing network messages


问:
Community Programming
Background

I just began working for a religious non-profit organization. As with most non-profits, the organization is resource-poor and has no IT department to speak of. In my two months here I've received 20 requests for websites, apps, and internal automation. Many of these 20 requests have merit and would benefit the organization.

I'm a .net web developer and as such the open source community is relatively foreign to me...

Question

For the sake of this question, lets say I'm talking about building a single, large, website.

Does software (web based, hopefully) exist that would allow me to post requirements and assets (graphics and CSS) for a site, and then invite programmers to participate in the sites development?

As a simple example, I could post the requirements and data for the about us page and an individual would indicate that they could/would fulfill the requirement. Upon completion, they could upload the new source code to the shared repository (github).

答:
You might consider using GitHub itself as the tool for this.  The requirements could be posted as individual "Issues" and you could have a special folder in the repository for "Requirements Assets" to place the assets associated with each issue/requirement.  Then other developers could fork the repository and pick up the issues to work on and post them as pull requests. And once they become trusted contributors just assign them to the project directly to post submissions.

You could use your existing website to request contributors, linking to the issues page and the repository page at the Github site.

Title: Community Programming