答:
I'm a Mercurial guy, I also use a little git.

I can tell you that in Mercurial editing / removing history is discouraged, but not impossible. Everybody lives calm with this way of doing things and I think it is a better way to go. Why edit the history unless you screw up?

Git enables you to edit history, but that doesn't mean you should. This creates problems for people, nothing really good comes out of it except a tidier history, but you shouldn't care as long as you keep your commits reviewable. My perception is that with Git, people can go OCD with the history editing power.

If you absolutely have to, however, never-ever-ever-ever modify history after pushing, you will make people mad.


问:
Fast compression in C++ and decompression in C#

Overview

I am working on a client-server application. The client is written in C++ (working on Windows, planning to support Linux) and the server is a .NET RESTful service. I need to HTTP POST some data to the server. The data is a unicode string that I need to compress using any fast compression algorithm (needs to be light on CPU). On the server I need to decompress raw bytes and get a string.

Problem

I cannot decompress raw bytes and I end up with decompressor's output buffers stay intact.

I tried

I have tried using Google Snappy, there is only a C/C++ version and any .NET ports don't appear to be finished. I also checked LZ4, where compression/decompression works in a single language, but when I try to use both - I cannot decompress data correctly (the decompressed bytes are set to 0s).

Question

Has anyone tried using a fast C/C++ compression and C# decompression? Any recommendations?

Client application shall not use more than 5% of CPU - that's a vague requirement I have. I plan to try gzip and maybe deflate, but I am not sure if I can configure compression levels there or whether it will work in both C/C++ and C#. Client collects some near real time data into a small buffer, when that buffer gets full it shall be compressed and POSTed. The whole OS process shall take less than 5% of the machine's CPU. A buffer is roughly posted 2 times a second which creates a traffic of about 2Kb/sec.

答:
Take a look at 7-zip's LZMA format. here

I have only used their compression utilities (but not their SDK) but they are excellent. The compression format is portable across language and platform and they claim support for both C# and C++

ContentLicense: CC BY-SA 3.0


问:
A startup as a web-application then later extended as mobile application. How to do it properly?
I have this idea that I want to build. I want to start the idea as a web-app, then move into mobile-app and possible desktop application.

The project should have databases (mostly strings). Also users would have accounts and access to these databases. So the project provides access to the user-resources through the Internet.
I want the database easily accessible through different platforms.
The project is also to sharpen my IT, so I don't want the easy road, but the better one.

What are my best options of frameworks/skills?

Good tools to manage the project?

Is starting as a web-app a good choice, or should I build it as a mobile-app first?

I have some knowledge (but not a lot of experience) in:

C, C++, Java, PHP, Javascript, MySQL, HTML/CSS.

Edit: I know that my question is too general, all I wanted is some ideas and guiding to have a good start.

@Nathan Taylor, regarding the web-app, I don't mind any option (should I learn Python, or stick with php in this regard)?

I'll probably implement the project in Android, and possibly iPhone.

答:
The shared part of your code will be the server-side component. I assume you will be building a set of web services, e.g. SOAP services. The various front-ends will all communicate with this same services API. It's very important to think long and hard about what API will be able to cater to all the target platforms and devices. Think about the different user expectations between a desktop and a mobile app, and what this means for the underlying API.

Don't bother trying to use the same client-side code for the different target platforms (mobile, web, desktop). You'll never get a solid user experience that way. For the various front-ends, it's probably best to focus on a single technology stack that can stretch to all the platforms you want to aim for. Otherwise you're going to drown in the amount of things to learn. Picking the web stack is a safe choice, because you can adapt it to mobile devices and to desktop devices with various solutions (e.g. Adobe Air, Sencha Touch, ...). If you absolutely have to you can pick up objective c for writing native iphone apps later.

If it were me, I would use the following technology choices:

Server-side: PHP or node.js

Client-side (web): Ext JS

Client-side (mobile): Sencha Touch

Client-side (desktop): Adobe Air

I'm not saying those are the best choices for you. They would just be the best choices for me.

ContentLicense: CC BY-SA 2.5


问:
I released open source code that is useable to other programmers. How do I let them know about it?
I have a tiny project (<1k but let's say its <5k of lines). I made it open source and put it on github.

I did this once before and I didn't get a single download nor fork but that was very specific and this tiny project is very useable to other programmers.

It's open source (let's say LGPL, GPL, public domain or somewhere in between these). What can I do other than let it rot on my computer/online while only I use it?

I'll keep this as generic as possible and won't link my stuff.

答:
I got a couple of projects at github ( http://github.com/jgauffin) which have received some users. What I do is:

Examples

Developers are lazy. If they can't figure out how to use your code they'll just continue to search after another library. Clear and concise examples are important

Documentation

When they have started to use your library they'll need some sort of documentation to be able to configure and use it as they whish. No doc = they'll give up.

Source code history

Users will always be skeptical to new projects. Not many open source projects survive. Just look at github/codeplex/sourceforge. there are a lot of abandoned projects. You can't expect users to dive in until you have proved that the project will continue to live.

Articles

Articles are a great way to attract new users. I blog ( http://blog.gauffin.org) and write articles at codeproject.com and other similar sites.


问:
Are exceptions an OOP concept?
Having read a post yesterday, I realized I did not know much about the origin of exceptions. Is it an OOP related concept only? I tend to think it is, but again there are database exceptions.</p>

答:
An exception is, simply put, an exceptional situation requiring attention and often a change in the flow of a program's execution. By that definition, exceptions and exception handling are not limited to object orientation, and simple program errors can be considered a form of exception.

Object oriented languages typically have a native exception class, and depending on context the word "exception" might indeed refer to that native class instead of the general concept. Object oriented exception handling is, as most of object orientation, syntactic sugar, and can be easily emulated in decisively non object oriented languages. Here's a C example, from the C Programming wikibook:

```<code>#include <stdio.h>
#include <setjmp.h>

jmp_buf test1;

void tryjump()
{
    longjmp(test1, 3);
}

int main (void)
{
    if (setjmp(test1)==0) {
        printf ("setjmp() returned 0.");
        tryjump();
    } else {
        printf ("setjmp returned from a longjmp function call.");
    }
}
</code>```

Title: Are exceptions an OOP concept?

Body:
An exception is, simply put, an exceptional situation requiring attention and often a change in the flow of a program's execution. By that definition, exceptions and exception handling are not limited to object orientation, and simple program errors can be considered a form of exception.

Object oriented languages typically have a native exception class, and depending on context the word "exception" might indeed refer to that native class instead of the general concept. Object oriented exception handling is, as most of object orientation, syntactic sugar, and can be easily emulated in decisively non object oriented languages. Here's a C example, from the C Programming wikibook:

#include <stdio.h>
#include <setjmp.h>

jmp_buf test1;

void tryjump()
{
    longjmp(test1, 3);
}

int main (void)
{
    if (setjmp(test1)==0) {
        printf ("setjmp() returned 0.");
        tryjump();
    } else {
        printf ("setjmp returned from a longjmp function call.");
    }
}


答:
Is it OOP related only?

No. Exceptions and OOP are unrelated.

Exceptions handling is a mechanism to handle errors. An exception is handled by saving the current state of execution in a predefined place and switching the execution to a specific subroutine known as an exception handler.

Comparing C (not really OOP language, possible to somehow emulate exceptions in C) and C++ (OOP, supports exceptions), nothing prevents C's standard committee from adding exceptions handling to C, it will still not make C an OOP language.

Title: Are exceptions an OOP concept?

Body: Having read a post yesterday, I realized I did not know much about the origin of exceptions. Is it an OOP related concept only? I tend to think it is, but again there are database exceptions.</p>


答:
The answer is a simple NO.

A good example for a non-OO language with exceptions is ADA.

Title: Are exceptions an OOP concept?


答:
Some very good answers here already. Other examples for non-OOP programming languages having exceptions:

Oracle PL/SQL

classic Visual Basic (V6 and below, "On Error Goto" is IMHO a form of exception handling)

(To be nitty: you find some OO elements in both of the languages, but the exception handling mechanics does not make use of them, I guess because the concept was introduced years before the OO elements were added to those languages).

Title: Are exceptions an OOP concept?


问:
Represent actions(verbs) in REST URI
I have a print operation to perform for my customer documents.
I need the other standard operations to be performed as well, like add,update, delete.
so, I have following:

For creating new customer:
URI = /customer/{id}, type = POST,
Methodname = CreateCustomer()

For updating:
URI: /customer/{id}, type = PUT, method =
UpdateCstomer()

For Delete customer:
URI = /customer/{id}, type =
DELETE, Methodname = DeleteCustomer()

For View:
URI: /customer/{id}, type = GET, method = GetCustomer()

Now, if I need to print a document for that customer, I need a print function.
My URI may look like this: /customer/{id}, type = POST , method = PrintCustomer().
But I have used that URI and POST type for CreateCustomer.
I wanted the URI to look like this:
/customer/Print/{id}, type = POST , method = PrintCustomer().

But I cannot have "Print" verb in my URI. Whats the best way to do this?
I thought about /customer/document/{id} as the URI... but I will run into the same issue.
I would have the CRUD operations on the "document". So, again I run out of what I would used for "print".
Please advise.

答:
I done this before. To print a document I just return a pdf version of a resource. The client only need to send a GET request for the resource with Accept header application/pdf.

This also avoid creating new URI for temporary resource like print job. Using HTTP header is also part of REST and it keeps the URI clean.

Title: Represent actions(verbs) in REST URI


问:
How will the new development of Java influence its interoperability with languages like Scala and Clojure?
As far as I understand, both Scala and Clojure have been designed as new languages that

depend on the JVM, and

easily integrate with Java code, in the sense that they allow to use Java classes inside Scala and Clojure code.

Starting with Java 8 (and maybe even more strongly with subsequent versions of Java), there will be changes in the semantics of the Java language.

I wanted to ask how these changes will impact the interoperability between Java and Scala / Clojure and what the consequences will be. For example, since lambdas in Java 8 are not objects (see e.g. here), Scala and Clojure might have to deal with Java values that are not objects. Would this be a problem?

I can think of the following scenarios:

The Scala or Clojure language will be extended to adapt to the new Java semantics (to handle the new non-object values) and support interoperability with Java.

The Scala or Clojure language will not be extended. This would only be possible if the new Java features like function values can be mapped to existing concepts. E.g., in Scala even a function is an object, so I guess Java functions would again be wrapped into some kind of objects when they become visible to Scala.

The Scala or Clojure language will continue to support interoperability up to Java 6 or 7, without following latest Java's development. This would require that older versions of Java be still supported (at least by OpenJDK or another project), so that these languages can be based on a more conservative / stable branch of Java.

Summarizing: can we expect that the future development of Java will have an impact on languages like Scala and Clojure to maintain interoperability with Java? Is there some (link to) ongoing discussion on this topic already?

Note

I can imagine that Scala, Clojure, and other JVM-based languages won't have any major problems updating their implementation to newer versions of the JVM (and that new JVM features will make this implementation even easier). My question focuses on features of Java as a language and whether / how other JVM-language will be able to "see" / use these new features, not on whether JVM-based languages will run on the latest JVM's.

答:
Actually Java 8 doesn't introduce much that will be detrimental to other JVM languages that interop with Java. The work done on Lambdas helped fix a number of small issues around invokedynamic, MethodHandles , MethodReferences etc - but apart from that it's carry on as normal.  That said, there's a whole new bunch of APIs that the other JVM languages could potentially call into now.  Which ones they'll use by default or not is up to them.

The largest change impacting interop actually came in with Java 7 - with the  invokedynamic bytecode that allows dynamic/late binding calls within the JVM - something that was initially designed for the other languages on the JVM.  It's since been very usefully adapted for Lamdbas, so as of Java 8, Java will actually start emitting these bytecodes.

Some languages (JRuby for example) are already heavily using invokedynamic, whilst others (Scala, Groovy et al) are still investigating its use or are in the early stages of patching it in.  In theory it makes their dynamic calls almost as performant as existing Java invokestatic calls, as opposed to the myriad of slower workarounds they were forced to use in the past.

Java 9 will bring more challenges for JVM languages with project Jigsaw coming into the platform which will be the beginning of the end for traditionally class loading and classpaths for the JVM.  The JVM language folks are pretty aware of this and I expect some sensible collaboration to take place.


问:
Loop fusion example using aspect-oriented framework
I had recently read a paper 'Aspect-Oriented Programming' by Gregor Kiczales and others, and found there the loop fusion example.

Here is a definition of the loop fusion from the paper

…the loop fusion composes by fusing the loops of those primitive
filters that have the same loop structure and that are direct
neighbors in the data flow graph.  Each of these composition rules is
easy to understand when looking at its own appropriate picture.  But
the two composition relation- ships cut each other so fundamentally
that each is very difficult to see in the other’s picture.

Later in the paper loop fusion mentioned to be implemented using metaobject protocol at Lisp:

…the loop fusion aspect … can be implemented, with some degree of
efficiency, using the method combination facility in the CLOS
metaobject protocol

What does loop fusion look like using any modern aspect-oriented frameworks in either static or dynamic typed languages? I'm looking for examples of aspect language and advices that could do loop fusion.

Status for mid-January'13

As long as there is no any other answer, I have marked my own answer as an answer. Anyway I'm still looking forward for examples from other languages/frameworks.

ps: loop fusion discusion at "AOP in .NET" book's forum @manning forum

答:
After initial paper released, Gregor Kiczales has started project AspectJ to implement an idea of Aspect-Oriented programming. Recently I found explanation why there are not "loop fusion" available at "AspectJ in Action" by Ramnivas Laddad:

In addition, the following are all join points: an object
  construction, a conditional check, a comparison, an exception handler,
  and even for, while, and do/while loops. Not all of the join
  points in a system are available for your use. … In order to prevent
  implementation-dependent or unstable crosscutting, AspectJ
  deliberately exposes only a subset of all the possible join points in
  the system. AspectJ, for example, does not expose for loops because
  you can easily change a for loop to a while loop that functions in the
  same manner. If such a change were to be made, all of the advice to
  the join point for the for loop would no longer be valid since the
  loop would no longer exist.

Another point I found at interview with Gael Fraiteur on PostSharp:

Some different people recommend AOP also for functional requirements
  and I... so really invasive in its aspects.  Using PostSharp, you are
  forced to design aspects so that aspects don’t know their target
  code.  They don’t know look how variables... so pay attention not to
  misuse PostSharp, not to misuse AOP, and respect also engineering
  principles, respect separation of concerns, and in the Java eco-system
  it is much, much longer concept and they have a lot of practice with
  it and users come with feel about that it’s more difficult to program
  with aspect because aspect has to know the target code. They have to
  know the implementation of target method and so on. Target method has
  to know they will be affected. I think this is a very bad design, and
  when you plan to use AOP, I recommend to design your base code and
  your AOP codes so that they don’t know about each other. It’s really
  important not to get completely mad with a small change.

So it's look like there is not "loop fusion" neither at AspectJ nor PostSharp, and Dynamic Proxy by it's definition could not provide this kind of functionality also


问:
User selection and object creation
I'm writing a GUI application. The user selects item from a comboBox (non editable). The suitable input data control is then enabled and user enters data. Then the appropriate object according to the comboBox selected item is created.

I've thought of using String[] array to display the list of choices and then using conditional statements to create the object.

Or create all the objects before user selects and set each object's properties accordingly after user data input.

I can't think of any better way to do this so I'd like to ask if there is one. If no, the first or the second way listed above is better?
Thank you.

答:
You could use the abstract factory pattern. For example, provide a list of subclasses of an abstract class VehicleFactory (say CarFactory, BicycleFactory, ...) . Create one object of each concrete factory class and associate the object with the combo box entries. After the user has chosen the entry, use the factory to create the particular Car, Bicycle ... object.

The factories should provide all the meta-information you need to control the GUI correctly, for example, the display name of each object, or which attributes the user has to enter for the particular object. The difference to what you wrote above in your comment is that you don't associate Vehicle objects directly with the combo box, but only factories.

Title: User selection and object creation


答:
Apparently those in need of your project, whose problems it intends to solve, have to be made aware of it.

I think Stack Overflow, as "The Wikipedia of Long Tail Programming Questions" is quite appropriate place for your target audience:

For every person who asks a question and gets an answer on Stack Overflow, hundreds or thousands of people will come read that conversation later. Even if the original asker got a decent answer and moved on, the question lives on and may continue to be useful for decades...

Stack Overflow practices and principles also can guide you on how to present your solution appropriately. Note these also apply beyond Stack Exchange network sites, it's just that here, these are stated explicitly and polished by vast practice of presenting problems and solutions to these.

As an experienced high rep SO user you are probably already well aware of these and in particular of the guidance given in below resources:

Stack Overflow -> How to Answer

Read the question carefully. What, specifically, is the question asking for? Make sure your answer provides that – or a viable alternative. The answer can be “don’t do that”, but it should also include “try this instead”. Any answer that gets the asker going in the right direction is helpful, but do try to mention any limitations, assumptions or simplifications in your answer. Brevity is acceptable, but fuller explanations are better...

SO FAQ - May I promote here?

Be careful, because the community frowns on overt self-promotion and tends to vote it down and flag it as spam. Post good, relevant answers, and if some (but not all) happen to be about your product or website, so be it. However, you must disclose your affiliation in your answers...

Note if you found no questions to "match the answer" you'd want to write, it is legitimate (and even encouraged) to submit your own question and answer it yourself. If you're interested in details, refer to MSO 'self-answer' tag wiki, there are quite helpful references to SE blog articles. You may also check some questions in that MSO tag to find out what can possibly go wrong and how to do it right.

Overall, your tactics can be pretty straightforward. Find (or write your own) description of the problem and write an answer explaining why and how it could be solved by your project. The better answer you write, the more chances for upvotes it gets, the better chances it will get to reach your target audience.

One thing to avoid is posting link-only-answers - as you probably already know, these are rather highly discouraged. Posting just a link to your project won't bring you much, you better give an easy to read and understand description of the project explaining what problems it solves and how.

Assuming that relevant questions may appear at any time, it may be difficult to be always ready to quickly give an answer of good quality. For your case, the most natural way to be prepared is to have a readme file right there in your project, with text that would be easy to just quote when needed to explain purpose and strong points of your project. Keep it under version control, update and polish the text in there and you'll always be in the best possible shape to send a message to your target audience.

In a small simple project, readme file like mentioned above can also serve a purpose of developer guide, having sections for usage examples, how to start, release notes etc.

Another thing you better be prepared to is to answer typical questions about your project. First of all, these could be like how to start and how to use - it could be very helpful to have "canned" answers to these in respective sections of readme file, as mentioned above. Note if you find some section gets too large, nothing prevents you from "extracting" it into separate file and just referring to it in your "main readme":

How to start.

Refer to file docs/QuickStart.txt

Usage examples.

Refer to file docs/UsageExamples.txt

Another kind questions from potential users one can always expect is "what if I discover an issue / bug in the project?" This kind of questions is best served by issue-tracking.

For a small simple project with little or no issues at all, this can be done as simple as just adding a section "Known issues" in readme file (if issue tracking eventually overgrows that, this will likely need to "migrate" to real tracking tool).

- what if I discover an issue / bug in the project?

- Update section "Known issues" in readme file

Even if you believe that for some reasons your project is bug-free, it is just easier to refer askers like above instead of giving them lengthy explanations for why you can't have bugs (especially taking into account that it's unlikely someone will believe in bug-free code:).

Title: I released open source code that is useable to other programmers. How do I let them know about it?

Body:
I have a tiny project (<1k but let's say its <5k of lines). I made it open source and put it on github.

I did this once before and I didn't get a single download nor fork but that was very specific and this tiny project is very useable to other programmers.

It's open source (let's say LGPL, GPL, public domain or somewhere in between these). What can I do other than let it rot on my computer/online while only I use it?

I'll keep this as generic as possible and won't link my stuff.


问:
We need a DVS. They need an SVN repo. What should we do?
We are a team of two people who need a versioning system for their university project. Due to administration issues, the graders need us to register on a site that happens to only support SVN; however, we cannot commit to SVN from inside the university as the required protocols are filtered out by the proxy (including the HTML extensions that would make SVN checkins over HTTP possible). Sigh.

Is it possible to have a hg repo for ourselves that can then be converted to SVN for purposes of hosting on this site?

Please note that practically all students commute to university, so the "we can't commit from university so we can't do this" is not as strong of an argument as you'd think.

答:
Well, if you only need to submit to the graders once then why do you need to use SVN at all until the final submission?  Just use a different repo and be done with it, then push to SVN when you are ready.  For day to day stuff use whatever you want.

If the inconsistent policies are not going to get fixed then I wouldn't worry too much about using the SVN repo they want or just commit off campus.


答:
If anybody interested I ended up using gzip from zlib. Never figured out why LZ4 doesn't work, as suggested in the comments this could be an endianess problem or a 64/32-bit mismatch. However, I tested this on a single machine compressing and decompressing a local file. The same compilation settings worked for gzip.

C/C++ sample compressor code

```<code>int compress_one_file(char *infilename, char *outfilename)
 {
    FILE *infile = fopen(infilename, "rb");
    gzFile outfile = gzopen(outfilename, "wb");
    if (!infile || !outfile) return -1;

    char inbuffer[128];
    int num_read = 0;
    unsigned long total_read = 0, total_wrote = 0;
    while ((num_read = fread(inbuffer, 1, sizeof(inbuffer), infile)) > 0) {
       total_read += num_read;
       gzwrite(outfile, inbuffer, num_read);
    }
    fclose(infile);
    gzclose(outfile);
 }
</code>```

C# sample decompressor code

```<code>public static void Decompress(FileInfo fileToDecompress)
{
    using (FileStream originalFileStream = fileToDecompress.OpenRead())
    {
        string currentFileName = fileToDecompress.FullName;
        string newFileName = currentFileName + ".decompressed";

        using (FileStream decompressedFileStream = File.Create(newFileName))
        {
            using (GZipStream decompressionStream =
                new GZipStream(originalFileStream, CompressionMode.Decompress))
            {
                decompressionStream.CopyTo(decompressedFileStream);
            }
        }
    }
}
</code>```

Title: Fast compression in C++ and decompression in C#

Body:
Overview

I am working on a client-server application. The client is written in C++ (working on Windows, planning to support Linux) and the server is a .NET RESTful service. I need to HTTP POST some data to the server. The data is a unicode string that I need to compress using any fast compression algorithm (needs to be light on CPU). On the server I need to decompress raw bytes and get a string.

Problem

I cannot decompress raw bytes and I end up with decompressor's output buffers stay intact.

I tried

I have tried using Google Snappy, there is only a C/C++ version and any .NET ports don't appear to be finished. I also checked LZ4, where compression/decompression works in a single language, but when I try to use both - I cannot decompress data correctly (the decompressed bytes are set to 0s).

Question

Has anyone tried using a fast C/C++ compression and C# decompression? Any recommendations?

Client application shall not use more than 5% of CPU - that's a vague requirement I have. I plan to try gzip and maybe deflate, but I am not sure if I can configure compression levels there or whether it will work in both C/C++ and C#. Client collects some near real time data into a small buffer, when that buffer gets full it shall be compressed and POSTed. The whole OS process shall take less than 5% of the machine's CPU. A buffer is roughly posted 2 times a second which creates a traffic of about 2Kb/sec.

Body:
If anybody interested I ended up using gzip from zlib. Never figured out why LZ4 doesn't work, as suggested in the comments this could be an endianess problem or a 64/32-bit mismatch. However, I tested this on a single machine compressing and decompressing a local file. The same compilation settings worked for gzip.

C/C++ sample compressor code

int compress_one_file(char *infilename, char *outfilename)
 {
    FILE *infile = fopen(infilename, "rb");
    gzFile outfile = gzopen(outfilename, "wb");
    if (!infile || !outfile) return -1;

    char inbuffer[128];
    int num_read = 0;
    unsigned long total_read = 0, total_wrote = 0;
    while ((num_read = fread(inbuffer, 1, sizeof(inbuffer), infile)) > 0) {
       total_read += num_read;
       gzwrite(outfile, inbuffer, num_read);
    }
    fclose(infile);
    gzclose(outfile);
 }

C# sample decompressor code

public static void Decompress(FileInfo fileToDecompress)
{
    using (FileStream originalFileStream = fileToDecompress.OpenRead())
    {
        string currentFileName = fileToDecompress.FullName;
        string newFileName = currentFileName + ".decompressed";

        using (FileStream decompressedFileStream = File.Create(newFileName))
        {
            using (GZipStream decompressionStream =
                new GZipStream(originalFileStream, CompressionMode.Decompress))
            {
                decompressionStream.CopyTo(decompressedFileStream);
            }
        }
    }
}


问:
How do you approach database design?
I am primarily a web developer and I have a couple of personal projects which I want to kick off.

One thing that is bugging me is database design. I have gone through in school db normalization and stuff like that but it has been a couple of years ago and I have never had experience with relational database design except for school.

So how you do you approach database from a web app perspective? How do you begin and what do you look out for? What are flags for caution?

答:
I do both object oriented programming and (mostly transactional, but some OLAP) database design, and for my circumstances, there are a lot of recurring themes (at least with OLTP).

Practicing 3nf normalization helps me to practice some variant of the single responsibility principle.  A table should represent a concept in your system - and concepts should relate to one another such that they attempt to mimick reality; for instance, if I'm building a system where a Customer can have 0 or many Activities, then I create a Customer Table, and an Activity Table.  The activity table has a foreign key relationship to the Customer table.  When I'm building stored procedures, I would make sure to use an outer join to join Customer and activity because the business requirement that a Customer can have 0 activities.

I also watch out for opportunities for extensibility by using bridge (link) tables.  For instance, if I were trying to represent a business rule where a book could have an unlimited (variable) number of authors, I would create a Book Table, an Author table, and a bridge/link table that has foreign key references to both Book and Author.

Also, I use surrogate keys on all tables (typically auto-incrementing identity columns, but perhaps Guids - the tradeoff with guids in code is that they take up more memory space than a simple integer), and I avoid relying on natural keys for my lookups (except with Bridge/Link Tables).  By default, I also create indexes on common foreign key columns, and review stored procedures/system queries from time-to-time to optimize indexing strategies.  Another indexing strategy I use is to look for places in my code where I build a collection based on a search column, and add appropriate indexes to search columns.

Title: How do you approach database design?


问:
Is it okay to mock multiple objects in one class?
For developers with extensive experience using mocks, is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended?

I am wondering because mocks are stubs anyway, from a testing perspective, it doesn't seem to make a big difference if I consolidate mocks.

However, I do wonder if there are negative impacts from a maintenance/clarity POV.

答:
Yes, it is perfectly fine.

One example I could think of is the MVP design pattern. If you pass model and view objects to the presenter with their interfaces, then you have to pass two mock objects in unit tests.


问:
Data representation with C# and WPF
I'm developing an application handling DB parts. I retrieve the data from the DB with stored procedures and prepared statements. Now I want to display the data in the GUI.

What is the current technology used for that? Does one still use DataSet and DataTable for that?

答:
There are different tools and different patterns.

Tools

ADO.NET

ADO.NET is much more than DataSet and DataTable. I would not use those classes in any project but instead use the IDataReader to populate pocos as I describe here: http://blog.gauffin.org/2013/01/ado-net-the-right-way/

Data mappers

The next step is to use a data mapper. What they do is to let you write SQL statements, but they will automatically return POCOs to you. Either as a dynamic representation or as T4 generated classes. (You can also map your own classes)

Some examples are Massive, PetaPoco and Simple.Data.

OR/Ms

Object/Relation mappers are the most complex approach (complex as in creating). They take care of everything for you. Most OR/Ms also has a LINQ to SQL provider. That is, you can write LINQ statements which then are converted to SQL.

Entity framework for instance has a visual designer in which you can point at the tables/columns that you want to get classes for. Hence it's quite easy to get started.

Examples: Lightspeed, Entity Framework and nhibernate.

Patterns

Patterns help you structure the code in the data access layer.

Repository pattern

Repository pattern is quite old but still a relevant pattern. The idea is to abstract away the data access to reduce coupling and complexity.

Query object

The query object pattern is used to create a class per query. For instance, it makes it easier to see which parameters are required (constructor arguments) and which are optional.

CQS

Command/Query separation is a way to separate querying (fetching) and commands (storing) information. It's not just a data access pattern but a way to structure your application.

CQRS

CQRS is similar to CQS but takes it a step further. It uses separate models (databases) for reads and writes. The read model is typically generated with the help of events from the writes.

WPF

In WPF you have view models which you use to map the GUI to your data access. You use ObservableCollection to get a GUI which responds to changes.

In the view model you'll use any of the tools that I described above (directly or through one of the described patterns).

Additional info

I've written a blog post about the data layer here: http://blog.gauffin.org/2013/01/data-layer-the-right-way/ where I discuss the data access.

imho stored procedures are obsolete. Parameterized queries are in many databases as fast as stored procedures.

Title: Data representation with C# and WPF


问:
Should your best programmers have to check everyone else's code into source control?
One of the differences between svn and git is the ability to control access to the repository.  It's hard to compare the two because there is a difference of perspective about who should be allowed to commit changes at all!

This question is about using git as a centralized repository for a team at a company somewhere.  Assume that the members of the team are of varying skill levels, much the way they are at most companies.

Git seems to assume that your only your best (most productive, most experienced) programmers are trusted to check in code.  If that's the case, you are taking their time away from actually writing code to review other people's code in order to check it in.  Does this pay off?  I really want to focus this question on what is the best use of your best programmer's time, not on best version-control practices in general.  A corollary might be, do good programmers quit if a significant portion of their job is to review other people's code?  I think both questions boil down to: is the review worth the productivity hit?

答:
No, it's a poor use of your best talent. Imagine a publishing company taking their most successful authors and making them do editing; bad idea.

There should be code reviews, but that doesn't mean it's always a Sr. checking a jr's code. Eventually, everyone on the team should be expected to get to the level where they can contribute code with minimal guidance. They go through the three levels of trust:

None - I want to see every line of code before you check it in.

Some - Let me know what you're doing and I'll provide feedback

Most - Go do your job and only ask for help when needed.

Advantages of freeing up your talent:

focus on design

involvement in setting up coding standards and enforcement strategies (without manually doing it all themselves)

tackle the tough coding problems

provide mentorship (without having approve every line of code)

There are developers interested in a management path who may prefer not to code all day long; leave the others alone.


答:
I can only think of a couple of situations where it might be a bad idea:

If your unit tests are part of the documentation (e.g. for a shared API) then you don't want to set a bad example. If you expect that real implementations would implement more than one interface then you can/should ignore this.

If your mock classes are anything more than simple stubs, then you risk making them unnecessarily complicated. Hopefully this falls under common sense!

With those exceptions, I don't see it being a problem.

Title: Is it okay to mock multiple objects in one class?

Body:
For developers with extensive experience using mocks, is it okay to mock multiple objects in one class (ie satisfy multiple interfaces) or is this not recommended?

I am wondering because mocks are stubs anyway, from a testing perspective, it doesn't seem to make a big difference if I consolidate mocks.

However, I do wonder if there are negative impacts from a maintenance/clarity POV.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: That because you're a programmer, you know how to fix [person]'s virus ridden machine.</p>


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答: How about some mixture of development and support (split roles)?   I think you'll still struggle to get buy-in for that because of reasons already mentioned (developers != product support people).  But if your product relies on a wide understanding of internal technology, maybe 80% development, 20% support would be a fair tradeoff.  Or some kind of mentoring/shadowing for new employees to ensure they get correct information about the product.</p>


答:
Code review doesn't necessarily require the attention of only your very best programmers. IMO, it should be an informal thing. Just a second opinion or a second pair of eyes on a piece of code from a non-rookie before it gets checked into production. It helps mitigate major oversights while also helping people get better at coding as a craft by being exposed to other dev perspectives.

Sort of a less-obnoxious pair-programming lite. In other words, it shouldn't take long and you shouldn't have to wait for somebody for hours. Anything in your development process that involves people waiting for things is a waste of money and crippling to momentum/morale, IMO.

If code review were meant to stop 99.5% of bugs before they got into your code base in the first place, there'd be no real point to sophisticated version control. That said, git is intimidating at first but basic general use isn't that complicated and it's highly configurable.. You should be able to stop for a few hours to teach everybody how to use it. Everybody commits. All but the noobiest rookies review until they demonstrate expertise at something.

Title: Should your best programmers have to check everyone else's code into source control?

Body:
One of the differences between svn and git is the ability to control access to the repository.  It's hard to compare the two because there is a difference of perspective about who should be allowed to commit changes at all!

This question is about using git as a centralized repository for a team at a company somewhere.  Assume that the members of the team are of varying skill levels, much the way they are at most companies.

Git seems to assume that your only your best (most productive, most experienced) programmers are trusted to check in code.  If that's the case, you are taking their time away from actually writing code to review other people's code in order to check it in.  Does this pay off?  I really want to focus this question on what is the best use of your best programmer's time, not on best version-control practices in general.  A corollary might be, do good programmers quit if a significant portion of their job is to review other people's code?  I think both questions boil down to: is the review worth the productivity hit?


答:
The basic idea behind exceptions is to clean up program flow so that a programmer can follow the "normal" execution path more easily. Consider a simple case of opening a file in C. Immediately after attempting to open the file, the programmer needs to examine the response from the fopen() call and decide if the call succeeded. If the call did not succeed, then the programmer must respond appropriately. The next call in the "normal" execution path, perhaps a call to fread() or fwrite(), would appear after the error or failure conditions have been handled. That may be on the next screen.

With a language that provides exceptions, the equivalent fopen() call can be followed immediately by the fread() or fwrite(). There is no error handling that is hiding the "next step" of the "normal" execution path. The programmer can see more of the normal path on a single screen, and so can follow the execution more easily. The error handling is moved to another part of the program.

Exceptions themselves are not an OOP concept, but they are often implemented using OOP concepts which make them more convenient and powerful. For instance, exceptions may be defined with an inheritance hierarchy. Using our notional example of opening and reading or writing a file, each of those calls may generate a variety of exceptions - FileClosedException, DeviceFullException, NoSuchFileException, InsufficientFilePermissionsException, etc. Each of those may inherit from FileException, which may inherit from IOException, which may inherit from GenericException.

If the programmer is doing a quick and dirty implementation to test a concept, he might mostly ignore exception handling and just implement a single handler for GenericException. That handler will handle a GenericException and any exception which inherits from GenericException. If he wants to treat any file related exception the same way, he can write a handler for FileException. That will be called for FileExceptions and any exceptions that inherit from FileException. If he wants to write a program that will respond differently to a variety of error conditions, he can write a specific handler for each specific exception.

Title: Are exceptions an OOP concept?


问:
Finding occurrences of a useful words and phrases in strings
I am building an app that analyzes posts by people by pulling their Tweets and Facebook posts. I need to process all the posts and find useful phrases. What I mean by useful is that, any word or phrase that is a noun/adjective/verb that would represent a discrete object or an idea, or in other words, I am looking for keywords.

For example, if someone has posted those three posts (in a very simple sense):

i am a big fan of progressive metal music! it is fantastic!

Look what I've found: a new Progressive Metal band!

a good genre in music is progressive metal

Analyzing those simple examples, I need to extract progressive metal and music with the highest occurrence rank. But if I pass the occurrences of words simply, I'll be getting a, is, I as the most common words. If I get away with the propositions, then I'll be getting single words such as progressive, metal, music. What I really need is to get phrases such as progressive metal, or progressive metal music, which together actually make sense. As a word, progressive and metal have other meanings, but the phrase progressive metal defines a musical genre, which has nothing to do with the single words themselves. Iteratively searching occurrence of every possible phrase in all the posts (e.g. first search i in all posts, then i am, then i am a etc.) is computationally extremely expensive and is not an option.

I've looked at some similar questions:

Available options for classifying words in text?

Language parsing to find important words

But both are overkills, solving (or trying to solve) more general problems. My problem is more specific and I'm thinking of a simpler solution that doesn't involve NLP. An idea one might come up with is to compare the posts against a valid word/phrase list, but people might be talking about a brand related name, or a specific event, that are not available in a dictionary, such as Twitter API, or death of Michael Jackson.

I am currently evaluating posts against the user's Facebook likes, which makes a good dictionary of valid phrases about the user, but it fails when we are on Twitter, without the notion of "likes", hence, no valid dictionary. Is there any simple way of checking occurrence of valıd terms in a large array of sentences? (not necessarily grammatically correct)

UPDATE: It's an iOS app so I'm in Objective-C, to keep in mind in library recommendations.

答:
A very rough outline how this could be done with Apache Solr.

Solr is a full text search engine with many setup options and very flexible ways to handle the indexing and faceting. Using the right combinations of tokenizers (split text in single elements, mostly words) and filters (post process the tokens like removing stop words as "a", "and", "I" etc or converting to lower case) you could get reasonable results. Especially since you can handle a single text in several ways at the same time by tokenizing and filtering it into more than one field.

Doing this would allow to index single words and word groups with or without stopwords. Running a facet search would count the occurrences of such words or groups.

The main work would be to find a good way to create the word groups. I'm not sure right now if one of the default tokenizers or filters would be good for that. Though you could write your own as a plugin in Java.

I guess there are better solutions with specialized tools, but I'm rather sure with Solr it could be done to a certain degree.


问:
Categories of 'for' loops
I remember once reading some research where a body of C code had been analysed, and the findings were that the vast majority of for loops could be categorised into about five categories, corresponding to the functional equivalents of map, filter, fold, etc.

I can't seem to find this paper/article anymore. Can anyone point me to it?

答:
This isn't an exact match for what you were requesting, but I think it gets pretty close to the root of your question.

This site's page on Loops discusses a number of looping patterns.

counting

filtered-count

accumulate

filtered-accumulate

search

extreme

extreme-index

filter

map

shuffle

merge

fossilized

missed-condition

They also have a page on Recursion that covers many of the same patterns in a recursive manner.

Title: Categories of 'for' loops


答:
I design objects first then I use an ORM (such as nHibernate) to create the schema. It gives me a lot more flexibility than doing the inverse.

The next step is optimization of the generated schema.

It has been a long time since I have seen a project where the database tables where designed first.

Title: How do you approach database design?

Body:
I am primarily a web developer and I have a couple of personal projects which I want to kick off.

One thing that is bugging me is database design. I have gone through in school db normalization and stuff like that but it has been a couple of years ago and I have never had experience with relational database design except for school.

So how you do you approach database from a web app perspective? How do you begin and what do you look out for? What are flags for caution?


答:
What is the current technology used for displaying Data? Does one still use DataSet and DataTable for that?

Well, taking into account your project needs it can really wary what to use, and what client design pattern to choose from.

However, the main point is not to over-complicate things (project design) that you are planning to achieve. Because, each design pattern has purpose to solve some common business problems, and implementing them for the sake of saying stating that project uses blah.. pattern has no value at all.

This is not to say that you should shun virtual functions, inheritance, or other features of modern programming languages. Far from it, often they not only add clarity and maintainability they also improve performance. But, as often, I find that people have written their code in some elaborate way when a much simpler model would have been equally servicable and more performant.

Thus, my advice would be to practice KISS and YAGNI principles.

Regarding MVVM pattern: It is a pattern designed to solve specific business problem which are combined under the term separation of concerns. Thus, you may consider it if it suits your project. For more readings on MVVM technical descriptions you may look here.

A good reading that may help you to clarify your decision regarding this pattern to look is - WPF Apps With The Model-View-ViewModel Design Pattern.

Title: Data representation with C# and WPF

Body:
I'm developing an application handling DB parts. I retrieve the data from the DB with stored procedures and prepared statements. Now I want to display the data in the GUI.

What is the current technology used for that? Does one still use DataSet and DataTable for that?

ContentLicense: CC BY-SA 4.0


问:
Database History Table / Tracking Table
Currently I want to structure a tracking/history table like this:

PrimaryKey - ID

OtherTableId - fk

fieldName - name of the field its tracking

OldValue

NewValue

UserName

CreateDateTime

So basically I want to have a table that will track another tables history, store the column name of the changed field with the new and old value. My question is can anyone poke holes in this? Also, what is the easiest way to ensure that only a column name from the tables its tracking is entered into the fieldName column? Currently my options are to have a enum in the service I'm building, or create another status table and make the fieldName  an  fk. Any better ideas?

Edit
Goal: There are currently only 2 fields that we care to track. One field will be shown on a web page to display history, the other field will only be accessed by one department and they have access to a view of the database which they’d be able to query. They’d be querying just this one field to get information on who changed the field and what to. This is the reason we wanted to set it where a database field defines the table column rather than having an exact copy of the table record history. We only want two fields tracked with the possibilities of adding or removing fields in the future.

Thanks!

答:
Poking holes: what if the database schema is changed at same point later in time, and a column name changes, or the column is deleted completely? Lots of database system allow this. What will happen to your "fieldName" then?

For data integrity: you must make sure that every update or delete operation will for sure update your tracking table. That is best accomplished by triggers calling a stored procedure. You should make sure only those stored procedure has writing access to your tracking table, so noone else can write wrong values.

If you can live with a db vendor specific solution: most db systems have system tables where the schema information (table names, table ids, column names etc) is stored. You can check if it is possible to set a foreign key reference to such a system table. That would allow to replace the field name by a field ID if the database supports something like this.

Actually, if you need to track whole rows of the specific table including all columns (and not just a small subset of the columns), you should consider @sarfeast's suggestion. Read this article about the drawbacks of name-value-pair models.

Title: Database History Table / Tracking Table


答:
The most successful change audit (history tracking) implementation I've seen is less generic and far simpler. It involves creating a change log table for each table you wish to monitor, keeping identical column names and data types (with an additional column for the time stamp).

The end goal, that is, what you'd like to do with the audited data will help evaluate how suitable each approach might be.

Title: Database History Table / Tracking Table

Body:
Currently I want to structure a tracking/history table like this:

PrimaryKey - ID

OtherTableId - fk

fieldName - name of the field its tracking

OldValue

NewValue

UserName

CreateDateTime

So basically I want to have a table that will track another tables history, store the column name of the changed field with the new and old value. My question is can anyone poke holes in this? Also, what is the easiest way to ensure that only a column name from the tables its tracking is entered into the fieldName column? Currently my options are to have a enum in the service I'm building, or create another status table and make the fieldName  an  fk. Any better ideas?

Edit
Goal: There are currently only 2 fields that we care to track. One field will be shown on a web page to display history, the other field will only be accessed by one department and they have access to a view of the database which they’d be able to query. They’d be querying just this one field to get information on who changed the field and what to. This is the reason we wanted to set it where a database field defines the table column rather than having an exact copy of the table record history. We only want two fields tracked with the possibilities of adding or removing fields in the future.

Thanks!


问:
How to do external API testing (blackbox)
Assume you are using APIs from a vendor, how to make sure their API is working as expected?

My main concern is sometimes the vendor pushed the changes to their code and break the API, we want to have some sort of automatic software to test them continually. How to deal with this?

答:
Implement learning tests for your area of interest (features that you plan to use). Learning tests are integration tests that are written by the developer against the public contract of the API. The tests should not be written against the internal implementation details even if the source code for the API is available. This kind of learning tests serves two purpose -

It dramatically improves your understanding of the third-party API.

The tests help to verify whether the claimed new version is actually backward compatible or not.


答:
Others have rightly answered "No" with examples of languages. I thought I could extend by adding an example on how to add exceptions to a language without ever involving OOP.

I will do this in case of the DSKL (Declarative Sequential Kernel Language) of OZ, a language well suited for academia stuff like this. The DSKL (or DKL) can be seen here (random search result), the Statements and Values part. The exact definition is not important, other than this being a very simple language with no modifiable variables (they are declared and later bound), and no OOP built in.

OOP can not even be added as an linguistic abstraction to this kernel language. By adding unique names to the kernel language (NewName) and using local scoping, encapsulation can be achieved. Or by adding a mutable state to the kernel language (NewCell) and using local scoping proper OOP with encapsulation can be achieved. But it can not be achieved with the specified kernel language alone.

If we then add exceptions to the kernel language we will have a language with no OOP-support but have exceptions. Let me show how:

Defining an abstract machine with a stack and a storage, we can define what each statement in our language should do (the semantics of the statement). For instance skip in the stack should do nothing, A = 3 in the stack should bind(/unify) A to(/with) 3.

We start by adding the syntax of how our exceptions should be defined. We do this by adding another two clauses to the <statement> in the DKL.

```<code><statement>  ::== ... (old stuff)
                 | try <statement> catch <id> then <statement> end
                 | raise <id> end
</code>```

Here is the known try/catch, and a way to raise/throw exceptions.

We define their semantics by how they should work on the abstract machine:

Try

The semantic statement is: (try <statement1> catch <id> then <statement2> end)

Do:

Push onto the stack the semantic statement (catch <id> then <statement2> end)

Push onto the stack the semantic statement (<statement1>)

Note that statement 1 will be on top of the stack, and tried executed first.

Raise

The semantic statement is: (raise <id> end)

Do:

If nothing more is on the stack, stop and report an uncaught exception.

Else, pop the first semantic statement from the stack. If it's not a catch statement, go to step 1.

We've gotten a catch, on the form (catch <id> then <statement> end)

Push (<statement>) onto the stack.

Catch

If we see a catch-statement during normal execution, this means that whatever was inside  executed without raising exceptions up to this level. Thus we just pop the catch of the stack and do nothing.

QED, we have a language with exceptions and no possibility of OOP.

I've removed the environment part from the abstract machine to make it simpler.

Title: Are exceptions an OOP concept?

Body:
Others have rightly answered "No" with examples of languages. I thought I could extend by adding an example on how to add exceptions to a language without ever involving OOP.

I will do this in case of the DSKL (Declarative Sequential Kernel Language) of OZ, a language well suited for academia stuff like this. The DSKL (or DKL) can be seen here (random search result), the Statements and Values part. The exact definition is not important, other than this being a very simple language with no modifiable variables (they are declared and later bound), and no OOP built in.

OOP can not even be added as an linguistic abstraction to this kernel language. By adding unique names to the kernel language (NewName) and using local scoping, encapsulation can be achieved. Or by adding a mutable state to the kernel language (NewCell) and using local scoping proper OOP with encapsulation can be achieved. But it can not be achieved with the specified kernel language alone.

If we then add exceptions to the kernel language we will have a language with no OOP-support but have exceptions. Let me show how:

Defining an abstract machine with a stack and a storage, we can define what each statement in our language should do (the semantics of the statement). For instance skip in the stack should do nothing, A = 3 in the stack should bind(/unify) A to(/with) 3.

We start by adding the syntax of how our exceptions should be defined. We do this by adding another two clauses to the <statement> in the DKL.

<statement>  ::== ... (old stuff)
                 | try <statement> catch <id> then <statement> end
                 | raise <id> end

Here is the known try/catch, and a way to raise/throw exceptions.

We define their semantics by how they should work on the abstract machine:

Try

The semantic statement is: (try <statement1> catch <id> then <statement2> end)

Do:

Push onto the stack the semantic statement (catch <id> then <statement2> end)

Push onto the stack the semantic statement (<statement1>)

Note that statement 1 will be on top of the stack, and tried executed first.

Raise

The semantic statement is: (raise <id> end)

Do:

If nothing more is on the stack, stop and report an uncaught exception.

Else, pop the first semantic statement from the stack. If it's not a catch statement, go to step 1.

We've gotten a catch, on the form (catch <id> then <statement> end)

Push (<statement>) onto the stack.

Catch

If we see a catch-statement during normal execution, this means that whatever was inside  executed without raising exceptions up to this level. Thus we just pop the catch of the stack and do nothing.

QED, we have a language with exceptions and no possibility of OOP.

I've removed the environment part from the abstract machine to make it simpler.


答:
You might want to check out NHibernate Envers project documentation for ideas.

Basically, you have one revision table where you can add extra data like a timestamp or user. Then, each table you track gets an additional audit table with all the columns duplicated, an fk to the revision table, and the type of revision (add, modify, delete). AFAIK, you wouldn't want your audit tables to have an actual FK to the real table because that would prevent deletes.

Title: Database History Table / Tracking Table


答:
In short: You need to set Audit Trail mechanism for the tables that you want to track the value change.

Single audit trail table:

Create a table to log the table name, field name abd old and new
  versions of the data. For this method it is usual to log both old and
  new versions of the data and only those fields that have changed. To
  implement this in triggeres it is a requirement that either there is a
  primary key on the table or only single rows are updated.

Here is a good post with scripts on how to achieve it - Creating Audit Trails

Other useful references to look:

Audit Trail – Tracing Data Changes in Database

Leaving an Audit Trail In Your Database

Title: Database History Table / Tracking Table


问:
Is every number in the code considered a "magic number"?
So every number in the code that we are sending to a method as an argument is considered as a Magic Number?
To me, it shouldn't.  I think if some number is let's say it is for minimum length of user name and we start using "6" in the code...then yeah we have a maintenance problem and here "6" is a magic number....but if we are calling a method that one of its arguments accept an integer for example as the ith member of a collection and then we pass "0" to that method call, in this case I don't see that "0" as a magic number.
What do you think?</p>

答:
If the meaning of the number is very clear in the context, I don't think it's a "magic number" problem.

Example: Let's say you're trying to get the substring of a string, from the beginning to some token and the code looks like this (imaginary language and library):

```<code>s := substring(big_string, 0, findFirstOccurence(SOME_TOKEN, big_string));
</code>```

In this context, the meaning of the number 0 is clear enough. I suppose you could define START_OF_SUBSTRING and set it to 0, but in this case I think it would be overkill (although it would be the correct approach if you knew that the start of your substring might not be 0, but that depends on the specifics of your situation).

Another example might be if you are trying to determine if a number is even or odd. Writing:

```<code>isEven := x % 2;
</code>```

is not as strange as:

```<code>TWO := 2;
isEven := x % TWO;
</code>```

Testing negative numbers as

```<code>MINUS_ONE := -1;
isNegativeInt := i <= MINUS_ONE;
</code>```

also feels weird to me, I'd much rather see

```<code>isNegativeInt := i <= -1;
</code>```

Body:
If the meaning of the number is very clear in the context, I don't think it's a "magic number" problem.

Example: Let's say you're trying to get the substring of a string, from the beginning to some token and the code looks like this (imaginary language and library):

s := substring(big_string, 0, findFirstOccurence(SOME_TOKEN, big_string));

In this context, the meaning of the number 0 is clear enough. I suppose you could define START_OF_SUBSTRING and set it to 0, but in this case I think it would be overkill (although it would be the correct approach if you knew that the start of your substring might not be 0, but that depends on the specifics of your situation).

Another example might be if you are trying to determine if a number is even or odd. Writing:

isEven := x % 2;

is not as strange as:

TWO := 2;
isEven := x % TWO;

Testing negative numbers as

MINUS_ONE := -1;
isNegativeInt := i <= MINUS_ONE;

also feels weird to me, I'd much rather see

isNegativeInt := i <= -1;


答:
This, as all principles, is a matter of degree. Generally speaking, number literals in source code are more suspect the larger they are. A maximum length like 10 or a memory address like 0x587FB0 are obviously bad practice - it is almost certain that sooner or later you will have to repeat these values more than once, creating a risk of incompatibility and subtle errors introduced in places that weren't changed.

0 is at the other end of the scale; it is still suspect but not quite as much.
Are you using 0 as a sentinel value? Then you should probably use a symbolic constant instead, just because the constant can explain what it means. Is it an extremely entrenched cultural agreement such as "0 means successful completion"? That's probably OK. Does it mean "the first item in a collection"? That may be harmless, but if there is an alternate method such as first() I'd probably prefer that.

Title: Is every number in the code considered a "magic number"?

Body:
So every number in the code that we are sending to a method as an argument is considered as a Magic Number?
To me, it shouldn't.  I think if some number is let's say it is for minimum length of user name and we start using "6" in the code...then yeah we have a maintenance problem and here "6" is a magic number....but if we are calling a method that one of its arguments accept an integer for example as the ith member of a collection and then we pass "0" to that method call, in this case I don't see that "0" as a magic number.
What do you think?</p>


问:
Is the carriage-return char considered obsolete
I wrote an open source library that parses structured data but intentionally left out carriage-return detection because I don't see the point. It adds additional complexity and overhead for little/no benefit.

To my surprise, a user submitted a bug where the parser wasn't working and I discovered the cause of the issue was that the data used CR line endings as opposed to LF or CRLF.

Hasn't OSX been using LF style line-endings since switching over to a unix-based platform?

I know there are applications like Notepad++ where line endings can be changed to use CR explicitly but I don't see why anybody would want to.

Is it safe to exclude support for the statistically insignificant percentage of users who decide (for whatever reason) to the old Mac OS style line-endings?

Update:

To clarify, supporting Windows line endings (ie CRLF) doesn't require CR token recognition. For efficiency purposes the lexer matches on a per-char basis. By silently ignoring CR chars, the CRLF token simplifies to LF. As such, the CRLF token itself could be considered an anachronism all its own but that's not what this question is about.

The last OS that provided system-wide support for CR style line endings was Mac OS 9. Ironically, the only application that still uses it as the default in OSX is Microsoft Excel.

答:
I would treat the request as any feature request where you need to weigh the costs against the benefits.

If exactly one person has asked for CR support, maybe it is not necessary. See the below book chapter from 37 signals where they say you should only worry about very popular feature requests.

http://gettingreal.37signals.com/ch05_Forget_Feature_Requests.php


问:
Does the state Pattern violate Liskov Substitution Principle?
This image is taken from Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

This is the class diagram for the State Pattern where a SalesOrder can have different states during its life time. Only certain transitions are allowed between the different states.

Now the OrderState class is an abstract class and all its methods are inherited to its subclasses. If we consider the subclass Cancelled which is a final state that doesn't allow any transitions to any other states, we'll have to override all its methods in this class to throw exceptions.

Now doesn't that violate Liskov's substitution principle since a sublcass shouldn't alter the behavior of the parent? Does changing the abstract class  into an interface fixes this?

How can this be fixed?

答:
This particular implementation, yes. If you make the states concrete classes rather than abstract implementors then you will get away from this.

However the state pattern you're referring to which is effectively a state machine design is in general something I disagree with from the way I've seen it grow. I think there is sufficient grounds to decry this as a violation of single responsibility principle because these state management patterns end up being central repositories for knowledge of the current state of many other parts of a system. This state management piece being centralized will more often than not require business rules relevant to many different parts of the system to reasonably coordinate them.

Imagine if all the parts of the system which care about state were in different services, different processes on different machines, a central status manager that details the status for each of those places effectively bottlenecks this whole distributed system and I think that bottleneck is a sign of a SRP violation as well as generally bad design.

In contrast, I would suggest one make objects more intelligent as in the Model object in the MVC pattern where the model knows how to handle itself, it doesn't need an outside orchestrator to manage it's internal workings or reason for it.

Even putting a state pattern like this inside of an object so it is only managing itself, it feels like you would be making that object too large. Workflows should be done through composition of various self-responsible objects I would say, rather than with a single orchestrated state which manages the flow of other objects, or the flow of intelligence within itself.

But at that point it's more art than engineering and so it is definitely subjective your approach to some of those things, that said the principles are a good guide and yes the implementation you list is an LSP violation, but could be corrected not to be. Just be very careful about the SRP when using any pattern of this nature and you're likely to be safe.


答:
```<code>bool hasApples = apples > 0;
</code>```

It is obvious zero means absence. I find 0 easier to understand than a variable named "absenceValue".

```<code>for(int i=0; i < arr.length; i++)
</code>```

It's obvious 0 is the starting position. I would be confused by a variable named "firstPosition". Such a variable would make me wonder if the starting position could change.

Body:
bool hasApples = apples > 0;

It is obvious zero means absence. I find 0 easier to understand than a variable named "absenceValue".

for(int i=0; i < arr.length; i++)

It's obvious 0 is the starting position. I would be confused by a variable named "firstPosition". Such a variable would make me wonder if the starting position could change.


答:
a sublcass shouldn't alter the behavior of the parent?

That's a common misinterpretation of LSP. A subclass can alter the behavior of the parent, as long as it remains true to the parent type.

There is a good long explanation on Wikipedia, suggesting the things that will breach LSP:

... there are a number of behavioral conditions that the subtype must meet. These are detailed in a terminology resembling that of design by contract methodology, leading to some restrictions on how contracts can interact with inheritance:

Preconditions cannot be strengthened in a subtype.

Postconditions cannot be weakened in a subtype.

Invariants of the supertype must be preserved in a subtype.

History constraint (the "history rule"). Objects are regarded as being modifiable only through their methods (encapsulation). Since subtypes may introduce methods that are not present in the supertype, the introduction of these methods may allow state changes in the subtype that are not permissible in the supertype. The history constraint prohibits this. It was the novel element introduced by Liskov and Wing. A violation of this constraint can be exemplified by defining a MutablePoint as a subtype of an ImmutablePoint. This is a violation of the history constraint, because in the history of the Immutable point, the state is always the same after creation, so it cannot include the history of a MutablePoint in general. Fields added to the subtype may however be safely modified because they are not observable through the supertype methods. One may derive a CircleWithFixedCenterButMutableRadius from ImmutablePoint without violating LSP.

Personally, I find it easier simply to remember this: If I'm looking at a parameter in a method that has type A, would someone passing a subtype B cause me any surprises? If they would then there is a breach of LSP.

Is throwing an Exception a surprise? Not really. It's something that can happen at any time, whether I'm calling the Ship method on OrderState or Granted or Shipped. So I have to account for it and it's not really a breach of LSP.

That said, I do think there are better ways to handle this situation. If I were writing this in C#, I would use interfaces and check for the implementation of an interface before calling the method. For example, if the current OrderState doesn't implement IShippable, don't call a Ship method on it.

But then I also wouldn't use the State pattern for this particular situation. The State pattern is much more appropriate to the state of an application than to the state of a domain object like this.

So, in a nutshell, this is a poorly contrived example of the State Pattern and not a particularly good way to handle the state of an order. But it arguably doesn't breach LSP. And the State pattern, in and of itself, certainly doesn't.

Title: Does the state Pattern violate Liskov Substitution Principle?

Body:
This image is taken from Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

This is the class diagram for the State Pattern where a SalesOrder can have different states during its life time. Only certain transitions are allowed between the different states.

Now the OrderState class is an abstract class and all its methods are inherited to its subclasses. If we consider the subclass Cancelled which is a final state that doesn't allow any transitions to any other states, we'll have to override all its methods in this class to throw exceptions.

Now doesn't that violate Liskov's substitution principle since a sublcass shouldn't alter the behavior of the parent? Does changing the abstract class  into an interface fixes this?

How can this be fixed?


问:
Shipping my first class library. Any gotchas I need to be aware of?
I'm a Web Developer about to unlock the "First Class Library Published" achievement in my career and I'm sweating bullets (I was up all night stressing out).  I'd love to tap the experience of the community to see if anyone has any suggestions or recommendations for making sure this goes as smoothly as possible.  Are there any specifics or gotchas I need to be aware of?  Anything special about the build process that can come back to bite me?

Here's where I'm at:

Library is unit tested and has approx 97% code coverage

API is well documented and xml docs for intellisense support have been created

I've ensured that public/private class accessors are accurate and correct. The same goes for all getters/setters

Error handling isn't as graceful as I'd like it to be, but I'm up against a deadline and have accepted that its an "as good as its going to be" for now

No friendly logging.  Debug.Writeline was used extensively...I've learned recently that this is a reflection of my inexperience :(

Your advice is greatly appreciated!

The library will be used to generate reports.  Standard hat -- connects to readonly database, performs calcs, formats and outputs data to response stream.

I was tapped as a fringe resource to fill in for one of the programmers that quit, and this task was given to me as a "cut your teeth" project.  The class library is going to be released for other programmers in the company to use while they write production code.

答:
These are two things that I find are key to releasing software:

Know exactly what you have released

Manage expectations

You want to be able to go back and bug fix what you have released and you want people to understand what problem your code will solve.

Knowing what you have released

Make sure you have it correctly versioned and signed (if approriate).  Use your source control to tag\label the code associated with the officially released version.  This will help you identify bugs easier as you can go back to exactly the source code you released.  It will also help down the line when you might have a few different released versions.

Try to make the latest version easy to get hold of and update.  Whether that's an installer, or simply putting it on a common share is dependent on who\when\how often you will be shipping.

Make sure that you have someone review your final release, including the documentation.  It's very easy to become nervous or excited about releasing software and miss something.

Managing expectations

Document the limitations and make them reasonably obvious to the developers.  It is good that you have found them.  People are often more understanding if they know the limitations with your software, especially if you have a plan to fix them.

Document how you would like feedback, good or bad.  As it is an internal project, if everyone has access to a common bug tracking system, ask them to file bugs against the appropriate project.

In the future, avoid changing the API if possible, this is the one thing that has the potential to annoy your customers.  Remember that exceptions are part of the API too, even though in C# they're not a part of the method documentation.  It may be possible to improve the exceptions being thrown at a later date, but you will need to talk to the end users and see what impact it will have.


问:
Do we achieve 100% Persistence Ignorance solution if we're not using ORM's POCO objects to model the Domain?
Persistence ignorance is ability to retrieve/persist standard objects, where standard objects are considered as classes focused on particular business problem  and thus don't contain any infrastructure-related logic. In DDD a Repository pattern is used to achieve PI.

Assuming we don't use ORM's POCO objects to model the Domain, then our Domain objects don't have to adhere to design requirements of a particular O/RM ( such as using default constructor or marking properties as virtual ). Such Domain objects would be considered Persistence Ignorant.

But if we want these Domain Objects to also support features such as lazy loading, then their properties must contain some logic which at some point would need to check whether related data was already loaded and if it wasn't, it would contact the appropriate Repository and request the related data.

Now even though these Domain Object are completely unaware of how they are being persisted and as such their Domain is completely decoupled from the underlying DAL provider, couldn't we still argue that such Domain Ojects contain Infrastructure-related logic and thus still violate PI?

答:
If you choose to not use ORM POCOs for your domain logic, fine. You also give up everything that come with them, such as lazy loading and caching, which become features that you need to account for (if you want) as part of your domain or assume they will be provided by the ORM at a lower layer.

Another challenge is the extra step to shuttle the data back and forth from the ORM POCOs to your Domain POCOs, which can be done with tools like Automapper but cause issues such as when updating an object you may need to force the ORM to retrieve it so it can be updated, depending on how the ORM is implemented.

How much are you really gaining by requiring 100% purity? Is not violating PI really so important?


问:
Dealing with Feature Intersections
I have recently witnessed more and more problems similar to the ones explained in this article on feature intersections. Another term for it would be product lines, though I tend to attribute these to actually different products, whereas I usually encounter these problems in the form of possible product configurations.

The basic idea of this type of problem is simple: You add a feature to a product, but somehow things get complicated due to a combination of other existing features. Eventually, QA finds a problem with a rare combination of features that no one thought of before and what should have been a simple bugfix may even turn into requiring major design changes.

The dimensions of this feature intersection problem are of a mind-blowing complexity. Let's say the current software version has N features and you add one new feature. Let's also simplify things by saying that each of the features can turned on or off only, then you already have 2^(N+1) possible feature combinations to consider. Due to a lack of better wording / search terms, I refer to the existence of these combinations as feature intersection problem. (Bonus points for an answer including reference(s) for a more established term.)

Now the question I struggle with is how to deal with this complexity problem on each level of the development process. For obvious cost reasons, it is impractical up to the point of being utopian, to want to address each combination individually. After all, we try to stay away from exponential complexity algorithms for a good reason, but to turn the very development process itself into an exponentially sized monster is bound to lead to utter failure.

So how do you get the best result in a systematic fashion that does not explode any budgets and is complete in a decent, useful, and professionally acceptable way.

Specification: When you specify a new feature - how do you ensure that it plays well with all the other children?

I can see that one could systematically examine each existing feature in combination with the new feature - but that would be in isolation of the other features. Given the complex nature of some features, this isolated view is often already so involved that it needs a structured approach all in itself, let alone the 2^(N-1) factor caused by the other features that one willingly ignored.

Implementation: When you implement a feature - how do you ensure your code interacts / intersects properly in all cases.

Again, I am wondering about the sheer complexity. I know of various techniques to reduce the error potential of two intersecting features, but none that would scale in any reasonable fashion. I do assume though, that a good strategy during the specification should keep the problem at bay during implementation.

Verification: When you test a feature - how do you deal with the fact, that you can only test a fraction of this feature intersection space?

It is tough enough to know that testing a single feature in isolation
guarantees nothing anywhere near error-free code, but when you reduce
that to a fraction of 2^-N it seems like hundreds of tests are not
even covering a single drop of water in all oceans combined. Even worse, the most   problematic errors are those that stem from the intersection of features, which one might not expect to lead to any problems - but how do you test for these if you don't expect such a strong intersection?

While I would like to hear how others deal with this problem, I am primarily interested in literature or articles analyzing the topic in greater depth. So if you personally follow a certain strategy it would be nice to include corresponding sources in your answer.

答:
We already knew mathematically that verification of a program is impossible in finite time in the most general case, due to the halting problem.  So this kind of problem is not new.

In practice, good design can provide decoupling such that the number of intersecting features is far less than 2^N, though it certainly seems to be above N even in well designed systems.

As far as sources, it seems to me that almost every book or blog about software design is effectively trying to reduce that 2^N as much as possible, though I don't know of any that cast the problem in the same terms as you do.

For an example of how design might help with this, in the article mentioned some of the feature intersection happened because replication and indexing were both triggered of the eTag.  If they had available another communication channel to signal the need for each of those separately then possibly they could have controlled the order of events more easily and had fewer issues.

Or, maybe not.  I don't know anything about RavenDB.  Architecture can't prevent feature intersection issues if the features really are inexplicably intertwined, and we can never know in advance we won't want a feature that really does have the worst case of 2^N intersection.  But architecture can at least limit intersections due to implementation issues.

Even if I'm wrong about RavenDB and eTags (and I'm just using it for the sake of argument - they're smart people and probably got it right), it should be clear how architecture can help.  Most patterns people talk about are designed explicitly with the goal of reducing the number of code changes required by new or changing features.  This goes way back - for example "Design Patterns, Elements of Reusable Object-Oriented Software", the introduction states "Each design pattern lets some aspect of the architecture vary independently of other aspects, thereby making a system more robust to a particular kind of change".

My point is, one can get some sense of the Big O of feature intersections in practice by, well, looking at what happens in practice.  In researching this answer, I found that most analysis of function points/development effort (i.e. - productivity) found either less than linear growth of project effort per function point, or very slightly above linear growth.  Which I found a bit surprising.  This had a pretty readable example.

This (and similar studies, some of which use function points instead of lines of code) doesn't prove feature intersection doesn't occur and cause problems, but it seems like reasonable evidence that it's not devastating in practice.

Title: Dealing with Feature Intersections


问:
Are exceptions an OOP concept?
Having read a post yesterday, I realized I did not know much about the origin of exceptions. Is it an OOP related concept only? I tend to think it is, but again there are database exceptions.</p>

答:
No.

IIRC, exceptions appeared before the first OO languages.  AFAIK, exceptions were first supported by early LISP implementations.  Early structured languages (e.g. ALGOL) and early OO languages (e.g. SIMULA) did not support exceptions.

Title: Are exceptions an OOP concept?


问:
Open sourcing an internal project that has confidential information in the old revisions.

Possible Duplicate:

  How to open-source a project whose git repository has copyrighted media in the history?

Our company has spent a year working on an internal web application and has decided to open source the project and host on github. The application was originally versioned with Bazaar and we are going to preserve the commit history when converting it to git.

There is some confidential information within the commit history, such as internal database information.

Question:

Is there a way to preserve the commit history while removing or hiding all traces of confidential information?

The big reason being that we have had employees that have worked on the project that have moved on to <s>higher-paying</s> other jobs and we want to maintain recognition of their hard work.

答:
GitHub has a help page on Removing sensitive data. This page describes in detail how to use git filter-branch to remove old commits that have sensitive information.

This is the general workflow you can use:

Convert the complete repository from Bazaar to Git.

Identify commit(s) that have confidential information.

Remove the confidential data with git filter-branch.

After you are satisfied that you have removed all the confidential information, then you can upload to GitHub.

To view the commit history, Git comes with the built-in gitk tool. I normally use tig which is a text mode repository viewer. There are many other possible repository viewers to choose from, your favourite IDE probably already has something built in.