问:
Instantiating Null Objects with Null-Coalescing Operator
Consider the following typical scenario:

```<code>if(myObject == null) {
    myObject = new myClass();
}
</code>```

I'm wondering what is thought of the following replacement using the null-coalescing operator:

```<code>myObject = myObject ?? new myClass();
</code>```

I'm not sure whether I should be using the second form. It seems like a nice shorthand, but the myObject = myObject construct at the beginning seems like it could be a bit of a code-smell.

Is this a reasonable thing to do, or is there a better shorthand that I am missing?  Or maybe, "It's three lines, get over it!"?

Edit:
As has been mentioned, perhaps calling this a typical scenario is something of an overstatement. I usually find that I encounter this situation when I'm retrieving an entity from a database that has a child reference type property that may or may not be populated yet:

```<code>myClass myObject = myClassService.getById(id);
myObject.myChildObject = myObject.myChildObject ?? new myChildClass();
</code>```

答:
I especially like using ?? in conjunction with optional method parameters. I limit the need for overloads and ensure the thing has a value.

```<code>public void DoSomething (MyClass thing1 = null) {
    thing1 = thing1 ?? new MyClass();
}
</code>```

Body:
I especially like using ?? in conjunction with optional method parameters. I limit the need for overloads and ensure the thing has a value.

public void DoSomething (MyClass thing1 = null) {
    thing1 = thing1 ?? new MyClass();
}


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答:
I want to offer an out-of-the-box idea: let's delete this comment altogether and then we don't have a problem how to phrase it.

The keyword abstract already says it all: one of the derived classes must implement the method.  If that's the intent you want to communicate to the implementors of those derived classes, then you're already using this particular language element appropriately.

ContentLicense: CC BY-SA 2.5


问:
What is the difference in meaning between "software", "program", "application", and "gadget"?
It seems to be a naive question, but I was unable to find an explicit definition and difference in meaning of the words "software", "program", "application", and "gadget". What is the correct (at least theoretically) way to use each of these words?</p>

答:
This is what I know from my understanding within the context of a desktops, mobile devices or servers.

Software: Requires installation that is hardware specific. For example Windows 7 is software, Microsoft office is software, etc. Main thing here is there is an installation process.

Application: Doesn't require installation, when downloaded can be run it without making it hardware aware. For example java applications can be run on macs and pcs without installation due the virtual machine. If you can drag the download to your desktop and just click the executable and it runs, it would be called an application.

Program: Instruction for a computer to follow. For example the code you would run in a batch  process is a program. There is no installation required, you are basically telling the computer to run some code to perform a task.

ContentLicense: CC BY-SA 3.0


问:
The right place to embed a parser : Server or the Client?
I'm writing a database management software. It has a client-server architecture where the server has the piece of code to store and retrieve. The client has to get the input from the user, connects to the server and queries it. Now I have a parser that can parse SQL like queries. My question is which is the best place to embed this parser?

Option 1-Embedding it in the Server:

Get the queries from the client, pass it untouched to the Server and then parse it and do the needful.

(OR)

Option 2-Embedding it in the Client:

Get the queries from the Client, parse it then and there and then pass a command object that has specific fields set reflecting the queries to the server and the server acts upon the data in the command object.

Which is the right way to do?

答:
There is no one right answer.  It depends on what you want to do.

If I understand you correctly, you're building a system that allows users to form SQL queries and submit them to your DBMS server.

If the users can be trusted to not submit malicious "DELETE FROM TABLE" commands, then either of your options would work.  If you have untrusted users, you have a lot of sanitizing work to do before you submit the query to the database.  The sanitizing must be done on the server.

Other concerns were mentioned in the comments, like how many different operating systems you want the client to run on.

In general, your client is untrusted and your server is trusted.  Generally, you will put as much processing as you can on your server, mostly for security reasons, somewhat for consistency reasons.  Performance will suffer.

If top performance is your primary concern, then put as much processing as possible on the client.  This allows you to serve the most clients with a given server.  However, security and consistency will suffer.


答:
It depends. If you need to query the server for getting a lot of metadata to do the parsing, then parsing on the client can cause a lot of additional roundtrips (additional to the ones for executing the query itself). On the other hand, if the client can parse the query and make a syntax check beforehand, without talking to the server, you may need less roundtrips than if you need to ask the server first to see if the query was syntactically correct.

Another question is if the parser needs a lot of CPU time; this would be a reason to place it on the client, to avoid getting your server a bottleneck.

And a third thing to consider is how easy it is to use the parser on the client or the server, which may depends to some degree on the programming languages you are using and how you actually do the embedding. I guess this is not a problem in your case (since it is so obvious you would otherwise would have mentioned it).

Title: The right place to embed a parser : Server or the Client?

Body:
I'm writing a database management software. It has a client-server architecture where the server has the piece of code to store and retrieve. The client has to get the input from the user, connects to the server and queries it. Now I have a parser that can parse SQL like queries. My question is which is the best place to embed this parser?

Option 1-Embedding it in the Server:

Get the queries from the client, pass it untouched to the Server and then parse it and do the needful.

(OR)

Option 2-Embedding it in the Client:

Get the queries from the Client, parse it then and there and then pass a command object that has specific fields set reflecting the queries to the server and the server acts upon the data in the command object.

Which is the right way to do?


答:
Adding to some of the good criteria stated already, like

Round trips.  Putting the parsing on the client can make the interace seem much more responsive.  If the users commits a simple syntax error, the feedback, through syntax highlighting can be instantaneous.

security.  Allowing an unsecured client over an unsecured communication channel to send in a rich construct like a command object that will be executed without additional checking on the server can be risky.  Yes, you can check the command object on the server, but then You have the same code in two places. Not ideal.

AND

Barring other other overriding concerns, my primary criterion for this problem, is the choice of language.   I find it orders of magnitude quicker and error free to implement parsing logic or other complex logic in a robust, clear language, such as those that are supported on the heavy duty server platforms.  EG, implementing parsing in JavaScript, trying to trace through a language that refuses to even give me a compiler error, if I accidentally get a typo in my variable name, and instead, declares another variable!, versus, C#.


问:
Looking for a book, blog or feed about anti-patterns
In my experience, being familiar with anti-patterns is as vital as knowing patterns themselves.

Despite an abundance of literature on patterns, there is a surprising lack of literature on anti-patterns. Browsing the web usually reveals advises that are either too vague (e.g. "do not use global variables"), too specific (e.g. "java.lang.Boolean.getBoolean doesn't do what you think it does") or obviously wrong to begin with (e.g. God object).

What I am looking for are anti-patterns that appear to be good solutions at first glance, but tend to lead to issues further down the line.

Do you know any good source of such anti-patterns? (the only good example I know is SQL Antipatterns)

答:
being familiar with anti-patterns is as vital as knowing patterns
  themselves

I agree! If you are avoiding all the anti-patterns then you are probably following the good patterns.

I recently took interest in finding anti-patterns and came across Wikipedia's Anti-Pattern Examples which has a large categorized list of anti-patterns and I wanted an alphabetical listing so I put all of them into an alphabetical list on my blog.

Related terms: code smell, dark patterns, common programming pitfalls, bad programming practices

Anti-patterns that might seem like a good idea at first:

premature optimization

overengineering

interface bloat

coding by exception


问:
Why is imperative programming preferred over functional programming?
Background: I am proponent of functional programming who works at a VB.NET shop where the prevailing mental model is imperative programming.  Being that foundation of our system is WinForms I can understand we're not going to get entirely away from imperative programming, but still I try to use FP (primarily via Linq) wherever possible because I believe in its merits.

Arguments & counter-arguments against FP

One might notice that fluent Linq is less efficient than its imperative counterpart in that this style processes a sequence down to another sequence and repeats that.  Generally, its going to take a few more passes than the imperative approach which can be better optimized to avoid repeat passes over a sequence.  For this reason, the lead couldn't understand why I would choose a functional approach that is clearly "less efficient."

Counter-argument: I argued that while it is sometimes less efficient in terms of CPU cycles, that I felt it is more humanly intelligible and easy to follow since each line does just one thing on its pass over the sequence.  To me this feels like having an assembly line where each person at his station has just one job to do.  I feel that the negligible trade off of efficiency is recompensed by code whose concerns are neatly separated.

The next argument against FP that I hear in my shop is that it's harder to debug -- which is true.  It's not easy to step over Linq code.  And I do sometimes have to unravel a method chain in order to better follow and dissect issues that I can't immediately spot.

_Counter-argument: For the most part though I don't have issue with this because I think the functional style is more declarative in how it reads and when an error is thrown within a functional chain, I can usually spot the issue immediately.

My Question

I've been trying to promote functional style in our shop and I don't feel like I'm making headway.  I've done both styles of programming and have only recently dabbled in Haskell.  Despite years of imperative experience, now that I'm making routine use of FP in JavaScript, it's grown on me.  It rings a note of rightness in my core when I compare it to what I might have done if I stuck to an imperative style.  I've retrained my brain toward functional thinking, toward functional composition.

What I can't understand is how hard its been to convince others of FP's merits.

For example, the developers in my shop do use Linq, but I think they generally use it in the context of dealing with domain data.  I use it in a more general sense and prefer it anytime I'm dealing with sequences/lists or persistent data structures.  I haven't been able to convince my teammates to expand their use of Linq.

What I'm trying to understand is what causes a developer to not like FP.

I would like to see an answer from someone who has a good deal of experience with FP but decided in favor of the imperative style.  What drove the decision to stay with imperative instead of using functional?

Here's an additional example highlighting the differences between imperative & functional programming.

I wrote the SelectedRows method of our grid in Linq as such:

```<code>Public Property SelectedRows() As DataRow() Implements IDataSourceControl.SelectedRows
    Get
        Return Me.ugrBase.Selected.Rows.
            OfType(Of Infragistics.Win.UltraWinGrid.UltraGridRow)().
            Select(Function(ugr) ugr.ListObject).
            OfType(Of DataRowView)().
            Select(Function(drv) drv.Row).
            ToArray
    End Get
</code>```

However, this style of code makes some of our developers uncomfortable and so our lead rewrote it to the more familiar:

```<code>Public Property SelectedRows() As DataRow() Implements IDataSourceControl.SelectedRows
    Get
        Dim plstRows As New List(Of DataRow)
        For Each bugrLoop As Infragistics.Win.UltraWinGrid.UltraGridRow In Me.ugrBase.Selected.Rows
            If bugrLoop.ListObject IsNot Nothing Then
                plstRows.Add(CType(bugrLoop.ListObject, DataRowView).Row)
            End If
        Next
        Return plstRows.ToArray()
    End Get
</code>```

答:
Functional programming is just too complicated for inexperienced programmers. One of the illustrations is this one, where students declared that 30-LOC mess was easier and more intuitive to understand compared to the four lines FP analog.

(This is the original version of the FP example, as the answer in the link has been more recently edited to make it slightly easier to read.)

```<code>return this.Data.Products
    .Where(c => c.IsEnabled)
    .GroupBy(c => c.Category)
    .Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));
</code>```

Functional programming requires a different way of thinking about the way we code and the way this code is executed. This is rarely the way the students are told in college, and once bad habits taken, it's difficult to change them.

Functional programming has also its own specific features which may appear risky in hands of beginners. Lazy evaluation is one of them, and it may take months before one starts to understand why lazy evaluation is an excellent feature, and not an annoyance.

That's also why so many beginners start programming with languages such as PHP and not languages like Haskell.

Body:
Functional programming is just too complicated for inexperienced programmers. One of the illustrations is this one, where students declared that 30-LOC mess was easier and more intuitive to understand compared to the four lines FP analog.

(This is the original version of the FP example, as the answer in the link has been more recently edited to make it slightly easier to read.)

return this.Data.Products
    .Where(c => c.IsEnabled)
    .GroupBy(c => c.Category)
    .Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));

Functional programming requires a different way of thinking about the way we code and the way this code is executed. This is rarely the way the students are told in college, and once bad habits taken, it's difficult to change them.

Functional programming has also its own specific features which may appear risky in hands of beginners. Lazy evaluation is one of them, and it may take months before one starts to understand why lazy evaluation is an excellent feature, and not an annoyance.

That's also why so many beginners start programming with languages such as PHP and not languages like Haskell.


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答: The I: integration.  A good text editor may be nice for writing code, but most of your programming isn't spent writing; it's spent testing and debugging, and for that you want your text editor to integrate with your compiler and your debugger.  That's the greatest strength of an IDE.


问:
How to model an arbitrary number of types
I'm currently in the process of modelling a generic form of RNA and RNA transcription and I'm having difficulty finding a proper OO modeling of this area.

Human RNA has 4 types of Nucleotides (A, G, U, and C).  An RNA strand is just a string of these 4 types.  eg, AAGACAUUCUA...

What I'm trying to model is more generic in the sense that I want to be able to decide the number of Nucleotide types at runtime.  So, my object model needs to be able to represent an arbitrary number Nucleotide types.

Initially, I thought I'd just have a Nucleotide class which had a int TypeId member.  This way, I could have a sequence of Nucleotide instances of arbitrary types... but this doesn't feel right.

I'm not a huge fan of storing type in a variable.  I'm also not comfortable with what is essentially definition information being set on every instance (instead of being defined in the a class).

So, how do I get around this?  Here's what I've come up with so far:

On a previous project, we would have Singleton objects which represented another object's type.  The other object would simply reference the singleton and that was it.  It prevented us from having multiple instantiations of the "definition" of our types.  Not too great IMO.

I remember Entity Framework generating Dynamic Proxies at runtime.  I could so something similar.  I could have a NucleotideBase base class and, at runtime, define derived classes.  I believe this is possible through reflection.  I'm not sure what the performance impact is with this approach, but I would assume it's all just one-time overhead when defining the classes.

Are there better, more OO, approaches?

答:
If a nucleotide has no significant behavior, and if its type information can be represented compactly (for example, a single character), then it doesn't deserve a separate class at all.  Simply represent each nucleotide as a character (or whatever).

If, however, a nucleotide has behavior, then I would model this with singletons, one instance per nucleotide type.

Since there is no difference in behavior in nucleotides, they are simple value objects.  A nucleotide instance should be immutable, so that all nucleotides of a given type can be represented by a single instance.

I would like to use the nucleotide's symbol as its type; this would be the sole instance variable of a Nucleotide.

A nucleotide factory can keep track of the singleton instances of nucleotide, creating a new instance when a new nucleotide type is asked for, or returning an existing instance otherwise.  Depending upon the language, it may be convenient for this factory to be implemented in static methods of the nucleotide class.


问:
Is it considered bad practice to compile into Javascript as a matter of language preference?
I understand that compiling into Javascript is sometimes necessary and even in some cases results in a faster application.

However I'm wondering if compiling into Javascript, for building web applications, from a language like ruby, is considered bad practice. Specifically for the purpose of language preference and for the task of doing typical front-end functions.

答:
In his article Javascript is assembly language for the web Scott Hanselman argues quite convincingly that JavaScript is a low-level language and that it makes perfect sense where possible to leverage a cross-compiler if that will make you more productive.

The same question could be asked regarding Assembly language. And while many people railed against the concept of higher level languages, they eventually lost that argument, just like the people who complained about the performance lost when using languages like Java and C# that don't compile to machine code but instead are compiled against a virtual machine (JVM or .NET Runtime, respectively).

JavaScript is like IL for the web, the fact that we can use higher-level languages to program JS means that we can be more productive and leverage the compiler to get good enough (and in many cases better) performance makes doing so a very good practice.

When I say low level, I mean metaphorically. Just as C lets us ignore things like registers and the like. Using a cross-compiler let's us ignore things like navigating/manipulating the DOM. We're removing ourselves from the details of what Javascript does and focusing on the logic of the app. This has enabled things like a full x86 emulator running linux in the browser or Unreal engine running in the browser

To answer Robert Harvey's Question, if you look at projects like LLVM, you can practically choose whatever language you'd like (and thus use whatever tools you like) and have it generate valid Javascript.

Also, as follow up, Scott asked the creator of JavaScript and the creator of JSON their views on the topic
Brendan Eich replied:

I said "JS is the x86 of the web" a couple of years ago [likely at JSConf], but I can't claim it's original. [Nick Thompson said it on Hacker News this year as well.]

The point is JS is about as low as we can go. But it also has higher-level facilities.
  Shaver's right, assembly without a great macro processor is not good for programmers or safety. JS is. So the analogy needs some qualification or it becomes silly.

The mix of high-level functional programming and memory safety, with low-level facilities such as typed arrays and the forthcoming ES.next extension of typed arrays, binary data, make for a more powerful programming language than assembly, and of course memory safety is the first differentiator.


问:
Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?

答:
If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call?

Yes.

This is why I sometimes use Find() functions to indicate that calling it may take awhile.  This is more of a convention than anything else. The time it takes for a function or attribute to return makes no difference to the program (though it might to the user), although among programmers there is an expectation that, if it is declared as an attribute, the cost to call it should be low.

In any case, there should be enough information in the code itself to deduce whether something is a function or attribute, so I don't really see the need to say that in the documentation.


答:
I think you understood him correctly, but I also think you have a good point. if Person.age is implemented with an expensive calculation, then I think I'd like to see that in the documentation too. It could make the difference between calling it repeatedly (if it's an inexpensive operation) or calling it once and caching the value (if it expensive). I don't know for sure, but I think in this case Meyer might agree that a warning in the documentation should be included.

Another way to handle this might be to introduce a new attribute whose name implies that a lengthy calculation might take place (such as Person.ageCalculatedFromDB) and then have Person.age return a value that's cached within the class, but this may not always be appropriate, and seems to overcomplicate things, in my opinion.

Title: Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?

Body:
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?


答:
You can write if a given call is expensive or not. Better, use a naming convention like getAge for quick access and loadAge or fetchAge for expensive lookup. You definitely want to inform the user if the method is performing any IO.

Every detail you give in the documentation is like a contract which has to be honored by the class. It should inform about important behavior. Often, you will see complexities indication with big O notation. But you usually want to be short and to the point.


答:
As a user, you don't need to know how something is implemented.

If performance is an issue, something has to be done inside the class implementation, not around it. Therefore, the correct action is to fix the class implementation or to file a bug to the maintainer.


问:
Whats the real overhead of TDD once the entire team is used to it?
What percentage of time is saved and costed doing TDD.

I assume this percentage of cost and reward changes during a projects life-cycle.

I'd imagine the initial phase has a lot more cost but little rewards attached. Further on (during re-factoring) you get the benefit of your tests.

I've heard anywhere from 30-50% of your time is writing unit tests. However that doesn't take into account the time saved from writing those tests. Whats the time saved as well as the time cost? In bug fixing and refactorablity?

答:
Each time you run your unit tests, you save yourself the amount of time it would have taken to manually test your code.

The 30% to 50% of time you quote as being required to write your tests is also offset a great deal by the benefits of having a better (testable) software design.

Let's say it takes four times as long to write an automated test as it does to manually perform the test.  That means that the fourth time you run your automated test, it pays for itself.  Every time you run the automated test after that, it's free.

This holds true whether the test is an automated unit test, or an automated functional test.  Not all functional tests can be automated, but many of them can.  Plus, the automated test is more reliable than a person; it will run the test in exactly the same way, every time.

Having unit tests means that you can refactor the underlying implementation of a method (for performance or other reasons), and the unit tests will verify that the functionality of the method has not changed.  This is especially true of TDD, where the unit test specifies the functionality of the method.

ContentLicense: CC BY-SA 4.0


答:
I wouldn't quite call it a bad practice. However, the further you are removed from JS in the language you're working in (in your case Ruby apparently), the greater the chance that the compiler will create errors. E.g. TypeScript is a close superset of JS, but I imagine that Ruby doesn't share a whole lot with JS (I could be wrong).

I don't particularly like JS myself, but I found that when trying to circumvent using a language, sooner or later it catches up with you and you'll still be forced to actually use that language. Might as well embrace it from the get-go.

Title: Is it considered bad practice to compile into Javascript as a matter of language preference?

Body:
I understand that compiling into Javascript is sometimes necessary and even in some cases results in a faster application.

However I'm wondering if compiling into Javascript, for building web applications, from a language like ruby, is considered bad practice. Specifically for the purpose of language preference and for the task of doing typical front-end functions.


问:
Naming convention of variables in C# programming language
I'm watching a video on C# about Variables. The author declares a variable inside a method and he named it like this: string MyName ="James";

my question is: which convention is recommended by .Net Framework. Is it Pascal casing as in the above example or is it camel case?

答:
I don't think there's something like an 'official' convention. As far as I know, the following is considered good practice by many  experienced C# developers:

PascalCase for public member variables (string MyName = "James")

camelCase for local variables (string myName = "James")

_leadingUnderscore for private member variables (string _myName = "James")

With this approach, one can distinguish between local variables as well as public and private members by the case of their first letter.

As with any coding convention, this is also subject to personal preferences. Therefore, there is no definite answer. A general goal should be to keep the code as readable and comprehensible as possible.


问:
Best practice to store DateTime based on TimeZone
Developing a web application which should allow User to schedule appointment based on their TimeZone. And I am storing the User scheduled datetime as server datetime into database field.  While showing schedule information retrieved the value from Database and converted into user timzone. processing in Code base I am converting the DateTime based on the user timezone.
Please suggest is this best practice or any easy way is exist?</p>

答:
It is important that you do not conflate two related concepts.

If you are manipulating an actual point in time, that is a specific time on a specific day, then the only way to do this is to always use the universal UTC time value.  Never attempt to store this as a timezone-relevant value.  When displaying this time value to a user, always convert to the user time zone at that time.  (And don't forget both the time and the date depend upon time zone.)

The other concept is that of a "time expression" such as "8:00PM every Tuesday".   You specifically mentioned allowing people to schedule appointments, and if you have recurring appointments, you need an expression like that.  I don't know of any standard expression language, but whatever you use, it will be relative to the time zone of the person who specified it.  It would be best to make this explicit  e.g. "8:00PM every Tuesday in Pacific Time Zone".   In the case of a time expression, you store this always as a string, and never involve any system time formats.

See more discussion of this on my blog


答:
The .Net Framework Naming Conventions (v4.5, v1.1) are agnostic about this.  They do not specify a standard for naming local variables.  You'll have to decide on your own convention for naming these.

I personally use camelCase, and disambiguate member variables from parameter names with this when necessary.  But leading underscores (i.e. _memberVariable) are also valid.

Title: Naming convention of variables in C# programming language

Body:
I'm watching a video on C# about Variables. The author declares a variable inside a method and he named it like this: string MyName ="James";

my question is: which convention is recommended by .Net Framework. Is it Pascal casing as in the above example or is it camel case?


问:
How/Where do I give my github commit a version?
I 'm just learning to give project versions.

I understand writing details about the changes in my project when committing, but where should I put my version number for my project?

答:
To build on MichaelT's answer, you can just add a Git "tag" to mark a particular commit as a canonical version of your code.

Assuming your most-recent commit on the master branch is the commit you would like to tag:

$ git tag 0.1.0

...or whatever version you would like to set it to. In the future, if you, or someone else would like to work with that specific version of your code, all that would need to be done (after an initial git-clone of your repository) would be to run:

$ git checkout tags/0.1.0

If you are looking for a sensible scheme to follow for your projects' versions, I highly recommend SemVer, as following a standard scheme for your projects' version makes it much easier to parse (if the need ever arises). SemVer also provides guidelines as to how to bump your version numbers.


问:
Will high reputation on Programmers help to get a good job?

Possible Duplicate:

  Will high reputation in Stack Overflow help to get a good job?

In reference to this question, do you think that having a high reputation on this site will help to get a good job?

Aside silly and humorous questions, on Programmers we can see a lot of high quality theory questions. I think that, if Stack Overflow will eventually evolve in "strictly programming related" (which usually is "strictly coding related"), the questions on Programmers will be much more interesting and meaningful ("Stack Overflow" = "I have this specific coding/implementation issue"; "Programmers" = "Best practices, team shaping, paradigms, CS theory").

So could high reputation on this site help (or at least be a good reference)? And then, more o less than Stack Overflow?

答:
I think many of the arguments given on the other question would also apply here, except applied to design and best practices as opposed to coding.

Maybe Joel should look for programmers on Stack Overflow, and managers and architects here.


答:
It's important to note that the first edition of this book was written in 1988, in the early days of OOP.  These people were working with more purely object oriented languages that are widely used today.  Our most popular OO languages today - C++, C# & Java - have some pretty significant differences from the way that the early, more purely OO, languages worked.

In a language such as C++ & Java, you must distinguish between accessing an attribute and a method call. There's a world of difference between instance.getter_method and instance.getter_method().  One actually gets your value and the other does not.

When working with a more purely OO language, of the Smalltalk or Ruby persuasion (which it appears that the Eiffel language used in this book is), it becomes perfectly valid advice.  These languages will implicitly call methods for you.  There becomes no difference between instance.attribute and instance.getter_method.

I wouldn't sweat this point or take it too dogmatically.  The intent is good - you don't want the users of your class to worry about irrelevant implementation details - but it doesn't translate cleanly to the syntax of many modern languages.


答:
I don't think Meyer's point is that you shouldn't tell the user when you have an expensive operation. If your function is going to hit the database, or make a request to a webserver, and spend several hours computing, other code is going to need to know that.

But the coder using your class doesn't need to know whether you've implemented:

```<code>return currentAge;
</code>```

or:

```<code>return getCurrentYear() - yearBorn;
</code>```

The performance characteristics between those two approaches is so minimal it shouldn't matter. The coder using your class really shouldn't care which you have. That's meyer's point.

But that's not always the case, for example, suppose you have a size method on a container. That could be implemented:

```<code>return size;
</code>```

or

```<code>return end_pointer - start_pointer;
</code>```

or it could be:

```<code>count = 0
for(Node * node = firstNode; node; node = node->next)
{
    count++
}
return count
</code>```

The difference between the first two really shouldn't matter. But the last one could have serious performance ramifications. That's why the STL, for example, says that .size() is O(1). It doesn't document exactly how the size is calculated, but it does give me the performance characteristics.

So: document performance issues. Don't document implementation details. I don't care how std::sort sorts my stuff, as long as it does so properly and efficiently. Your class also shouldn't document how it calculates things, but if something has an unexpected performance profile, document that.

Body:
I don't think Meyer's point is that you shouldn't tell the user when you have an expensive operation. If your function is going to hit the database, or make a request to a webserver, and spend several hours computing, other code is going to need to know that.

But the coder using your class doesn't need to know whether you've implemented:

return currentAge;

or:

return getCurrentYear() - yearBorn;

The performance characteristics between those two approaches is so minimal it shouldn't matter. The coder using your class really shouldn't care which you have. That's meyer's point.

But that's not always the case, for example, suppose you have a size method on a container. That could be implemented:

return size;

or

return end_pointer - start_pointer;

or it could be:

count = 0
for(Node * node = firstNode; node; node = node->next)
{
    count++
}
return count

The difference between the first two really shouldn't matter. But the last one could have serious performance ramifications. That's why the STL, for example, says that .size() is O(1). It doesn't document exactly how the size is calculated, but it does give me the performance characteristics.

So: document performance issues. Don't document implementation details. I don't care how std::sort sorts my stuff, as long as it does so properly and efficiently. Your class also shouldn't document how it calculates things, but if something has an unexpected performance profile, document that.


答:
From an academic or CS purists view, it is of course a failure to describe in the documentation anything about the internals of the implementation of a feature. That's because the user of a class should ideally not make any assumptions about the internal implementation of the class. If the implementation changes, ideally no user won't notice that - the feature creates an abstraction and the internals should kept completely hidden.

However, most real-world programs suffer from Joel Spolsky`s "Law of leaky abstractions", which says

"All non-trivial abstractions, to some degree, are leaky."

That means, it is virtually impossible to create a full black-box abstraction of complex features. And a typical symptom of this are performance issues. So for real world programs, it may become very important which calls are expensive and which are not, and a good documentation should include that information (or it should say where the user of a class is allowed to make assumptions about performance, and where not).

So my advice is: include the information about potential expensive calls if you write docs for a real-world program, and exclude it for a program which you are writing only for educational purposes of your CS course, given that any performance considerations should be kept intentionally out of scope.


答:
I think SO rep would be better for getting you a great coding job.

Programmers rep more accurately reflects your ability to impress people with subjective BS.  Therefore, programmers rep will be better for getting you a job in management. ;)

Title: Will high reputation on Programmers help to get a good job?

Body:
Possible Duplicate:

  Will high reputation in Stack Overflow help to get a good job?

In reference to this question, do you think that having a high reputation on this site will help to get a good job?

Aside silly and humorous questions, on Programmers we can see a lot of high quality theory questions. I think that, if Stack Overflow will eventually evolve in "strictly programming related" (which usually is "strictly coding related"), the questions on Programmers will be much more interesting and meaningful ("Stack Overflow" = "I have this specific coding/implementation issue"; "Programmers" = "Best practices, team shaping, paradigms, CS theory").

So could high reputation on this site help (or at least be a good reference)? And then, more o less than Stack Overflow?


问:
Should I keep my GitHub forked repositories around forever?
So I've forked someone else's repository, made a few changes, submitted a pull request, and my changes made it into the product. Great!

But...what should I do with my forked repository? Is there a compelling reason for me to keep my repository around, or should I go ahead and delete it? I don't plan on making any additional contributions, but if I change my mind I assume I can always just re-fork it.

I'm not really concerned about keeping a backup. I'm more worried about breaking links, losing commit messages, etc.

答:
If your pull request got accepted and you haven't made any other changes that you might use personally, you should delete it.

Deleting doesn't harm anything.

You can always refork if you need to

It cuts down on useless repos in search results when people are searching for something

If you use your GitHub as a sort of resume for potential jobs/contracts, it looks better if you don't have dozens of forked repos that you're not currently working on. You'll appear more efficient.

It helps your own sanity when you don't have to page through hundreds of useless repos.

Its better for GitHub. :)


答:
I would use  byte TypeId instead of int TypeId, because when you make RNA strands with long lists of Nucleotides, you don't want to waste 4 times of the memory you really need. The TypeId should be the only member attribut of that struct. If you need additional information for some operations, try to use the Flyweight pattern. So a List<Nucleotide> with 1000 elements will need almost exactly 1000 bytes in memory, with neglectable overhead (in C#).

if you don't expect different behaviours for different Nucleotide types, it feels complety wrong for me to use different derived classes for representing the types. Don't overcomplicate things - only because different derived classes can technically be used for distinguishing types, it is not always the best solution.

Title: How to model an arbitrary number of types

Body:
I'm currently in the process of modelling a generic form of RNA and RNA transcription and I'm having difficulty finding a proper OO modeling of this area.

Human RNA has 4 types of Nucleotides (A, G, U, and C).  An RNA strand is just a string of these 4 types.  eg, AAGACAUUCUA...

What I'm trying to model is more generic in the sense that I want to be able to decide the number of Nucleotide types at runtime.  So, my object model needs to be able to represent an arbitrary number Nucleotide types.

Initially, I thought I'd just have a Nucleotide class which had a int TypeId member.  This way, I could have a sequence of Nucleotide instances of arbitrary types... but this doesn't feel right.

I'm not a huge fan of storing type in a variable.  I'm also not comfortable with what is essentially definition information being set on every instance (instead of being defined in the a class).

So, how do I get around this?  Here's what I've come up with so far:

On a previous project, we would have Singleton objects which represented another object's type.  The other object would simply reference the singleton and that was it.  It prevented us from having multiple instantiations of the "definition" of our types.  Not too great IMO.

I remember Entity Framework generating Dynamic Proxies at runtime.  I could so something similar.  I could have a NucleotideBase base class and, at runtime, define derived classes.  I believe this is possible through reflection.  I'm not sure what the performance impact is with this approach, but I would assume it's all just one-time overhead when defining the classes.

Are there better, more OO, approaches?


问:
Doesn't single-assert unit testing break the DRY principle?
Whenever I write unit tests I have always tried to have a single assert per test to make debugging easier when tests fail. However as I follow this rule I feel like I am constantly copying the same code in each test and by having more tests it becomes harder to go back to read and maintain.

So does single-assertion testing violate DRY?

And Is there a good rule to follow to find a good balance, like just having one test per method?*

*I realize there probably isn't a one-size fits all solution to this but is there a recommended way to approach this?

答:
Proper unit tests have a naming convention that helps you immediately identify what has failed:

```<code>public void AddNewCustomer_CustomerExists_ThrowsException()
</code>```

This is why you have one assertion per test, so that each method (and it's name) corresponds to the condition that you are asserting.

As you've correctly pointed out, each new test is going to have similar setup code.  As with any code, you can refactor the common code into its own method to reduce or eliminate the duplication and make your code more DRY.  Some testing frameworks are specifically designed to allow you to put that setup code in one place.

In TDD, no test is YAGNI, because you write tests based only on what you require your code to do.  If you don't need it, you won't write the test.

Body:
Proper unit tests have a naming convention that helps you immediately identify what has failed:

public void AddNewCustomer_CustomerExists_ThrowsException()

This is why you have one assertion per test, so that each method (and it's name) corresponds to the condition that you are asserting.

As you've correctly pointed out, each new test is going to have similar setup code.  As with any code, you can refactor the common code into its own method to reduce or eliminate the duplication and make your code more DRY.  Some testing frameworks are specifically designed to allow you to put that setup code in one place.

In TDD, no test is YAGNI, because you write tests based only on what you require your code to do.  If you don't need it, you won't write the test.


答:
No. This seems to be just the way you're doing it. Unless you've found a notable reference where they claim this is a good practice.

Use a test fixture (although in XUnit terminology the set of tests, the setup and tear down is the fixture), that is, some set up or examples that applies to all your tests.

Use methods like you would normally to structure your code. When refactoring tests the usual TDD Red-Green-Refactor does not apply, instead apply, "Refactoring in the Red". That is,

deliberately break your test,

do your refactoring

fix your test

This way you know that the tests still give positive and negative results.

There are several standard formats for tests. For example, Arrange, Act, Assert or Given When, Then (BDD). Consider using a separate function for each step. You should be able to call the function to reduce boilerplate.

Title: Doesn't single-assert unit testing break the DRY principle?

Body:
Whenever I write unit tests I have always tried to have a single assert per test to make debugging easier when tests fail. However as I follow this rule I feel like I am constantly copying the same code in each test and by having more tests it becomes harder to go back to read and maintain.

So does single-assertion testing violate DRY?

And Is there a good rule to follow to find a good balance, like just having one test per method?*

*I realize there probably isn't a one-size fits all solution to this but is there a recommended way to approach this?


答:
So does single-assertion testing violate DRY?

No, but it promotes violation.

That said, good object oriented design tends to go out the window for unit tests - mostly for good reason. It's more important that unit tests be isolated from one another so that the test can be interrogated in isolation and if need be, fixed with confidence that you don't break other tests. Basically that test correctness and readability is more important than its size or maintainability.

Frankly, I've never been a fan of the one assert per test rule for the reasons you describe: it leads to a lot of boilerplate code that is hard to read, easy to mis-boilterplate, and hard to fix well if you refactor (which drives you to refactor less).

If a function is supposed to return a list of "foo" and "bar" for a given input, but in any order it is perfectly fine to use two asserts to check that both of them are in the result set. Where you get into trouble is when a single test is checking two inputs or two side effects and you don't know which of the two caused the failure.

I view it as a variation on the Single Responsibility Principle: there should be only one thing can cause a test to fail, and in an ideal world that change should only break one test.

But in the end it's a trade off. Are you more likely to spend more time maintaining all the copy pastey code, or will you spend more time hunting down root causes when tests could be broken by multiple sources. As long as you write -some- tests, it probably doesn't matter too much. Despite my disdain for single-assert tests, I tend to err on the side of more tests. Your mileage may vary.


问:
What are some well known applications written in F#?
As part of a continuing quest for knowledge, I'm spending some time this week learning the basics of F# as an introduction to functional programming. I think I am understanding the construction of software under this model and some of the proposed benefits, but am still a little fuzzy on the real-world use cases.

I was hoping that a F# success stories, or at least a few applications that I'd be familiar with might make it a little clearer about when F# (or any functional programming language) would be appropriate for a project.

So back to the question, what are some well known applications that use F# or a similar functional programming language?

BTW: I am also open to hearing about some lesser-known apps, but if you mention one, please give the basics of what the app is about and why the language used was the appropriate choice.

答: There is Tabbles. A file manager and organizer, with a lot of features. It provides a tagging system that you can even share with others. It's a commercial product.</p>


答:
Any programmer-oriented piece of documentation which fails to inform programmers about the complexity cost of routines/methods is flawed.

We are looking to produce side effect-free methods.

If execution of a method has run time complexity and/or memory complexity other than O(1), in memory- or time-constrained environments it can be considered to have side effects.

The principle of least surprise is violated if a method does something completely unexpected - in this case, hogging memory or wasting CPU time.


问:
What does it mean for the JSON interchange format to have a license?
A recent flurry of comments on a JSHint issue alerted me to the fact that the JSON data-interchange format has a license.

The content of this license can be debated elsewhere.

What I'm unclear on is what it means for JSON (or any other data-interchance format) to have a license.

If an a library simply consumes and parses JSON, does it have to include this license? I understand that using a library that contains this license would require a user to include it. I'm talking about writing a library from scratch.

What if I have to use JSON because a third party service only communicates via JSON. If I'm serializing and deserializing data according to the RFC, do I still need to refer to the license?

答:
Note that the license refers to the reference implementation of JSON, not to the JSON format itself.

As an aside, I find it amusing that people get so worked up over the "not evil" clause.  See this Douglas Crockford video for some perspective.


问:
best way to store data from ajax call
I am writing a web-application in which I am retrieving data's from server through AJAX requests and the generate HTML content dynamically.
I have some data to load, generate HTML from it and append into my web page.
Now I was thinking on two solutions:

1) Do AJAX call, generate HTML from response, set display: none to it when I need, and when I'll need it later, set display: block; instead and hide() other content I don't need to display (always dynamically generated).

2) Save AJAX response into variables, remove HTML generated before, re-generate from variable when I'll need it later.

I don't know if I explained it well, but I would like to know which is best practice in terms of client/server performance.

答:
The first approach you suggest, rendering the HTML into a hidden div is reasonable, particularly if the information returned by the service is unlikely to change once it has been rendered and you don't need to manipulate the variable any further.  This avoids rendering the content more than once. From your description, it sounds like this is the basic need that you need to fill.  Note, if you use display:none, any size or position calculations you do within the rendered area will not work properly.  So, if you are dynamically sizing or placing any elements, they may not render properly.  For simple HTML, this probably won't be a problem. </p>

<p>If you need to manipulate the result after it is received, or you are making the request multiple times and need to render the HTML anew each time because the response may have changed, a better approach would be to parse the response into an object and render it into the HTML using a function taking the object as input, or even better, using a templating system like the one included in the Underscore.js library to render the HTML.  </p>

Title: best way to store data from ajax call

Body:
The first approach you suggest, rendering the HTML into a hidden div is reasonable, particularly if the information returned by the service is unlikely to change once it has been rendered and you don't need to manipulate the variable any further.  This avoids rendering the content more than once. From your description, it sounds like this is the basic need that you need to fill.  Note, if you use display:none, any size or position calculations you do within the rendered area will not work properly.  So, if you are dynamically sizing or placing any elements, they may not render properly.  For simple HTML, this probably won't be a problem.

If you need to manipulate the result after it is received, or you are making the request multiple times and need to render the HTML anew each time because the response may have changed, a better approach would be to parse the response into an object and render it into the HTML using a function taking the object as input, or even better, using a templating system like the one included in the Underscore.js library to render the HTML.


问:
what's a good approach to working with multiple databases?
I'm working on a project that has its own database call it InternalDb, but also it queries two other databases, call them ExternalDb1 and ExternalDb2.  Both ExternalDb1 and ExternalDb2 are actually required by a few other projects.  I'm wondering what the best approach for dealing with this is?

Currently, I've just created a project for each of these external databases and then generated Edmx and entities using the entity-framework approach.  My thought was that I could then include these projects in any of my solutions that require access to these databases.  Also, I don't have any separate business layers. I just have a solution like below:

```<code>Project.Domain
ExternalDb1Project.Domain
ExternalDb2Project.Domain
Project.Web
</code>```

So my Domain projects contain the data access as well as the POCOs generated by Entity Framework and any business logic.  But I'm not sure if this is a good approach.  For example if I want to do Validation in my Project.Domain on the entities in the InternalDb, it's fine.  But if I want to do Validation for entities from either of the ExternalDbs, then I wonder where it should go?  To be more specific, I retrieve Employees from ExternalDb1Project.Domain.  However, I want to make sure they are Active.  Where should this Validation go?

How to architect a project like this at a high level?  Also, I want to make sure that I use IoC for my data contexts so I can create Fakes when writing tests.  I wonder where the interfaces for these various data contexts would reside?

答:
You could treat them as standalone resources. That is, do what you've done, but continue by exposing the data via a service. So instead of including the project references in client projects, include service references.

Then, whatever validation is required by the data is done in the service, and whatever validation logic is only required in/by the client is done in the client.

It depends on your data/clients/security/volume/connectivity requirements as to what type of service you want to expose (OData/REST/etc).


问:
When was the earliest time that the term "snake case" was used?
Many people use the term Snake Case to describe variables or other symbols with_the_form_of_underscores.

In the past week, I've launched several broad searches. I can't find anything about the origin of this term that is more detailed than what Wikipedia says (above)

When did the earliest record of this term enter into use?

答:
A person named Jack Dahlgren claims on Quora he invented the term in 2002 when he worked at Intel.

Here's what he posted at above link:

I believe that I am the one who coined this term back in 2002 when I
  was at Intel and we were evaluating Sharepoint Team Services. Based on
  the unfortunate tendency of Sharepoint to escape spaces in names with
  [underscore] characters (among other things) I recommended a policy of
  using underscores to replace all spaces so that URLs would be slightly
  shorter and much more readable.

Given the existing "camelCase" name with humps in the middle, I called
  it "snake_case" or if there were two flat spots, I jokingly called it
  "road_kill_case". Considering the size of Intel and my interactions
  with Microsoft product team, it is possible that this is the origin,
  but it is such a simple phase that I think it could have been invented
  independently elsewhere too.


答:
do you think that having a high
  reputation on this site will help to
  get a good job?

Maybe in the future, but right now it seems to have very little relevance.


问:
ASP.NET and windows applications
Currently I'm still learning ASP.NET. My goal is to build dynamic websites. However, I also want to be able to build some windows applications as well.

So, is it easy to learn Windows forms or WPF after ASP.NET? or is the reverse easier? meaning to start with WPF then move to ASP.NET?

答:
I would say it's easier to move to WinForms/WPF from ASP.NET than the other way. This is due in large part to the fact that ASP.NET has statelessness to overcome, as well as being inherently multi-user plus having a far larger variety of technologies which you have to integrate at once. To top all that off you have a whole host of reliability issues built into the fact that it's a combination of network resources that completes an ASP.NET website.

These are all issues that you will either not see at all, or very very minimally in desktop applications. There are however a minimum of desktop application issues you will see that are not also facts of ASP.NET development as well. The only real common desktop application problem that ASP.NET doesn't have is machine dependencies, with ASP.NET you control the server and manage what's installed on it, with desktop applications you have to manage dependencies on the deployment environment by way of some installer or other such. Also there's the presentational thread that you have to be mindful not to block, but the threading you deal with in ASP.NET is umpteen times more complex than this, so managing that is quite easy.

Title: ASP.NET and windows applications


问:
How to charge customers for AGPL-3 based solution?
If I talk about openERP its and source (AGPL-3), I have studied it, but can't find some question e.g

1: we have developed a School Management System using openERP Version 7.0, as according to my understanding, we cannot sale it to any customer as it appears to be free like other modules of openERP.

So I should charge my client for my services? what should be the criteria for that? OR still there is a chance that I can sell my newly developed module?

答:
You can sell your application. There is no limitation on this.

But you have to provide the source code of your created application to your customer if he wishes and your customer can do whatever he wants with the application (even giving it to other people for free).

You can charge your service e.g. developing extensions for your application or fixing bugs. But the customer has also the possibility to fix the bugs himself as he has the source code of the application.

You can also run the application (either on your server or by administrating your customers server) and charge your customer for this.

So there are several ways to get money for your work.


答:
Absolutely

not

You have >1k rep on Programmers.SE? Great for you!


问:
The right place to embed a parser : Server or the Client?
I'm writing a database management software. It has a client-server architecture where the server has the piece of code to store and retrieve. The client has to get the input from the user, connects to the server and queries it. Now I have a parser that can parse SQL like queries. My question is which is the best place to embed this parser?

Option 1-Embedding it in the Server:

Get the queries from the client, pass it untouched to the Server and then parse it and do the needful.

(OR)

Option 2-Embedding it in the Client:

Get the queries from the Client, parse it then and there and then pass a command object that has specific fields set reflecting the queries to the server and the server acts upon the data in the command object.

Which is the right way to do?

答:
There is no one right answer, but keep in mind that:

Client must not be trusted. In any context even slightly related to security, either the client or the network communication is usually easy to attack. So server must never trust client but must always validate everything.

Over network the data is always serialized in some way, so the server needs some kind of parser. It might be a lot simpler than the one to parse the original input, but it is still a parser.


问:
Writing my own voice recognition code
Problem Description

I am wanting to use voice recognition as part of a hardware project, which I would like to be completely self containing (I'm using small low power, low speed devices such as Arduino's and Raspberry Pi's, Kinects etc, no running traditional computer with an OS is involved. So a closed / self containing project).

Voice recognition can be very complicated depending on the level of sophistication you desire. I have what I believe a comparatively simple set of requirements. I only want to recognise my own voice, and I have a small dictionary of 20 or so words I'd like to recognise. Thus I don't require complex speech-to-text and voice recognition libraries or any of the excellent 3rd party software I find via Internet search engines (there is no shortage of these!). I believe my requirements are "simple enough" (within reason) that I can code my own solution. I am wondering if anyone has written their own process like this, and is my method is massively flawed? Is there a better way to do this without requiring a high level of mathematics or having to write a complex algorithm? That is the solution I have tried to think up below.

Solution Description

I will be writing this in C but I wish to discuss a language agnostic process, focussing on the process its self. So lets ignore that if we can.

1 . I will pre-record my dictionary of words to match those being spoken. We can imagine I have 20 recordings of my 20 different words, or perhaps short phrases or sentences of two or three words. I believe this makes the process of comparing two recording files easier than actually converting the audio to text and comparing two strings.

2 . A microphone is connected to my hardware device running my code. [1]. The code is continuously taking fixed length samples, say 10msec in length for example, and storing 10 consecutive samples for example, in a circular logging style. [2]. (I'm inventing these figures off the top of my head so they are only examples to describe the process).

[1] This would likely be connected through a band-pass filter and op-amp, as would the dictionary recordings be made, to keep the stored and collected audio samples smaller.

[2] I'm not sure exactly how I will take a sample, I need to work out a method though were I produce a numerical figure (integer/float/double) that represents the audio of a 10msec sample (perhaps a CRC value or MD5 sum etc of the audio sample), or a stream of figures (a stream of audio readings of frequencies perhaps). Ultimately a "sample" will be a numerical figure or figures. This part is going to be much more hardware involved so not really for discussion here.

3 . The code looks at it's stored 10 consecutive samples and looks for a volume increase to indicate a word or phrase is being said (a break from silence) and then increases is consecutive sample collecting to say 500 samples for example. That would mean it captures 5 seconds of audio in 10 msec samples.

It is these samples or "slices" that are compared between the stored sound and captured sound. If a high enough percentage of samples captured matched the equivalent stored ones, the code assumes its the same word.

```<code>The start of a store recording of the world "hello" for example,
stored words are split into 10 msec samples also

Stored Sample No           | 1| 2| 3| 4| 5| 6| 7|  8|
Stored Sample Value        |27|38|41|16|59|77|200|78|

Incoming audio (me saying "hello") with some "blank" samples
at the start to symbolise silence

Incoming Sample No         | 1| 2| 3| 4| 5| 6| 7| 8| 9|10| 11|12|
Incoming Sample Value      |  |  |  |20|27|38|46|16|59|77|200|78|
</code>```

4 . Once the code has collected a full sample stream, it then chops off the blanks samples at the start to produce the following audio recording. It could also move the sample set backwards and forwards a few places to better align with the stored sample.

This produces a sample set like the below:

```<code>Stored Sample No           | 1| 2| 3| 4| 5| 6|  7| 8|
Stored Sample Value        |27|38|41|16|59|77|200|78|

Incoming Sample No      |-1| 1| 2| 3| 4| 5| 6|  7| 8|
Incoming Sample Value   |20|27|38|46|16|59|81|201|78|
</code>```

5 . I believe that by having a percentage value for how close each sample must be, so sample 7 differs by a value of 1 which is less than %1, and a percentage value for the total number of samples which must be within their sample matching percentage, the code has an easily tunable level of accuracy.

I have never done anything like this with audio before, it could be a lot of work. This is why I am asking this question, if you perhaps already know the answer to this question to be obvious (what ever that answer may be). I am hoping this won't be a computationally massive tasks as some of the hardware I will be using will be low sec stuff. In the hundreds of Megahertz (Maybe 1Ghz using an over-clocked Rasp Pi). So this is a rather crude way to match audio samples using lower computational power. I'm not aiming for instant results, but less than 30 seconds for a decent proof of concept.

PS
I don't have the rep to tag this with a new tag like "audio", "audio recognition", "voice", "voice recognition" etc.

答:
Well i don't believe the Arduino has the horse power to do this. its operating at 16Mhz
An Arduino has about 32K of memory. Even 20 words sampled in Mp3 (smaller then wav) wouldnt fit in it, despite its only your own voice.

The rasberi pi might do the trick, its operating at 700Mhz depending on the version it might have 512MB memory. That's still not a lot dough.

You might need a fourier
(http://www.drdobbs.com/cpp/a-simple-and-efficient-fft-implementatio/199500857)

Or if you intend to use volume, do a few averages with previous samples like

x= ( x + x[n-1] + x[n-2] + x[n-3] ) / 4  // thats quite simple might need more

A next thing you need to do is i think if you would plot these X values
Then you need some kind of slope detection of that line
Because detecting commands based on volume depends otherwise a lot on distance
While you would rather like to detect the pattern of the words

Then it depends a bit how to record the slope so that the pattern would fit another time.
I mean one doesnt speak in the exact tempo a computer can match
and slope can be a bit steeper. In the end i think this is a bit how steep those lines are and their length y axis, should be within some average

Title: Writing my own voice recognition code


问:
License for academic use only?
I'm developing a software package and would like to make it (and the source) available for personal, academic, or educational use, but not for commercial use. Is there such a license? Ideally, it should be reciprocal, so that if someone publishes a modified version, they'll have to grant the same rights.

Alternatively, would it be possible to modify the GPLv3 in such a way that it forbids commercial use and grants rights only to non-commercial users?

答:
I know of a project (omnet++) that does something similar. The license gives permission for personal, academic, or educational use, but not for commercial use: https://omnetpp.org/intro/license

They say that the license is kind of similar to the GPL.

ACADEMIC PUBLIC LICENSE
  ...This license contains the terms and conditions of using OMNeT++ in noncommercial settings: at academic institutions for teaching and research use, and at non-profit research organizations. You will find that this license provides noncommercial users of OMNeT++ with rights that are similar to the well-known GNU General Public License, yet it retains the possibility for OMNeT++ authors to financially support the development by selling commercial licenses. In fact, if you intend to use OMNeT++ in a "for-profit" environment, where research is conducted to develop or enhance a product, is used in a commercial service offering, or when a commercial company uses OMNeT++ to participate in a research project (for example government-funded or EU-funded research projects), then you need to obtain a commercial license for OMNeT++. In that case, please contact the Author to inquire about commercial licenses.

What are the rights given to noncommercial users? Similarly to GPL, you have the right to use the software, to distribute copies, to receive source code, to change the software and distribute your modifications or the modified software. Also similarly to the GPL, if you distribute verbatim or modified copies of this software, they must be distributed under this license.

By modeling the GPL, this license guarantees that you're safe when using OMNeT++ in your work, for teaching or research. This license guarantees that OMNeT++ will remain available free of charge for nonprofit use. You can modify OMNeT++ to your purposes, and you can also share your modifications. Even in the unlikely case of the authors abandoning OMNeT++ entirely, this license permits anyone to continue developing it from the last release, and to create further releases under this license...

Title: License for academic use only?


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答: IDE's understand your code much better than an editor.  This allows for instance for identifier completion and refactoring, which for verbose languages like Java is a God-send,</p>


问:
Pair Programming/Collaboration in a small company
I work at a small development company as the lead developer. We have two other developers, as well as my boss who is a developer, but doesn't really do much of the actual coding anymore.

The problem I am trying to overcome is multifaceted. We have a tendency all to work on our own projects without much collaboration between us. As a matter of fact, I (as the most advanced developer) ask for the others' opinion/help more than they do mine, because I value the input of an outside eye.

I want to increase our collaboration, and have expressed that to them. In large part because I'd like to show them some things about how to become better developers and follow better practices. But given our other developers' personality types, I think they are more comfortable working alone.

I've been reading about pair programming, and I have read (in some forums) that it doesn't work well when you have one developer being more advanced than the others (which I am). And yet, I feel it is imperative that we start to collaborate so that our work is not so disparate.

My question is whether anyone has ever been in a similar situation, and what worked for them?

I realize this is not a one-size-fits-all situation, but I'm willing to give multiple approaches a shot.

We all work in a common area, developers don't have have individual offices / cubicles.

答:
TL;DR: I don't think pair programming would work for you. Instead you should try to get people concerned about the long-term quality of their code and make them want to find answers. This has to be done informally.

About culture and quality

I feel this issue is not about programming methodology but rather about culture.
In my experience, culture is possible to direct, but rarely by telling people about it. That is, trying to force a certain workflow on people that hadn't evolved naturally or is too far removed from the existing practice is bound to have negative consequences.

In other words, you don't want to look like the suit who comes around buzzing the latest buzzwords, even when ultimately you are. Most programmers I know would mentally tag you as background noise. Don't be a corporate bee.

In my opinion, the primary question you should be asking yourself is "am I happy with the quality and business value of the code my organization puts out?" and if the answer to that is negative, you should ask "how do I turn this around?".

Ultimately, quality and value are human definitions only you or someone else in your organization can (and should) think about.

Pair programming and micromanagement

So, at the risk of sounding a bit forward and harsh, it seems to me that reading about pair programming actually got you thinking about some form of micromanagement, or the other way around. MM is a sure-fire recipe for alienating most people.

In defense of pair programming: pair programming is not about some guy looking over some other guy's shoulder. That is as micro as management gets. PP is about using two minds to think about two levels at the same time - one person deals with high-level, big picture issues while the other takes care of the nuts and bolts needed to produce working code. And in my humble opinion, it rarely works well if the two participants are not in a position to switch places. They ought to be similarly-experienced enough to have a similar professional arsenal of concepts and a shared professional vocabulary (we're not mind-linked - yet, muhahaha).

For your situation, I'd say since you're a small team and you're the only one with real experience (that's what your post sounds like to me), pair-programming or reviewing most of the code most of the time wouldn't work. You only have 24 hours a day. Instead, some solutions you could consider:

Encourage them to participate in SO under the appropriate language tag, or to post some code snippets for review on Code Review SE. Start a little informal contest over who can gain the most SO rep points per week.

SO can do wonders for newbie developers since it provides constant feedback and follows the heartbeat of the community.

Take a look at some of the code they check in and challenge them informally with some questions concerning its long-term evolution. Most beginner programmers are simply not accustomed to thinking about making their code readable and maintainable. Once you get those issues into their heads, they'll seek more information on their own, from you or other sources.


问:
Offline data transaction processing capabilities in a context of poor internet connectivity
We have a core banking product developed with ASP.NET with C# using Microsoft SQL Server 2008 database. Product is hosted on a centralized server and works well at all locations (bank branches) where connectivity is good and stable.

We need to implement this solution at a region where connectivity is always an issue. Since it is a core-banking solution, there should not be any service lapse to the customer because of technical issues (viz., connectivity).

How to design the architecture for this and ensure that there is no transactional issues at any given point of time, and at the same time the centralized database contains the latest data from all branches?

答:
How to design the architecture for this and ensure that there is no transactional issues at any given point of time, and at the same time the centralized database contains the latest data from all branches ?

In short: For the serious network connectivity issues between branches, it is not possible to have a real-time solution.

However, as a trade-off solution you may come up with nightly "data synchronization process" to central database/repository when network connectivity is stable. Drawback would be having a one day old information in central database. This is still a good solution for reporting purposes, however, for transactionl real-time solution it would not be sufficient.

As an additional food for thought, you may consider distributed queuing approach, as it will pile-up the requests to the main central server while the connectivity is lost or unstable. Once the network connectivity gets up, it will sent them in an order.

Overall, this requires a trade-off, rather than a working real-time solution for systems with connectivity problems.


问:
Algorithm for tracking progress of controller method running in background
I am using Codeigniter framework for PHP on Windows platform. My problem is I am trying to track progress of a controller method running in background. The controller extracts data from the database(MySQL) then does some processing and then stores the results again in the database. The complete aforesaid process can be considered as a single task. A new task can be assigned while another task is running. The newly assigned task will be added in a queue. So if I can track progress of the controller, I can show status for each of these tasks. Like I can show "Pending" status for tasks in the queue, "In Progress" for tasks running and "Done" for tasks that are completed.

Main Issue:

Now first thing I need to find is an algorithm to track the progress of how much amount of execution the controller method has completed and that means tracking how much amount of method has completed execution. For instance, this PHP script tracks progress of array being counted. Here the current state and state after total execution are known so it is possible to track its progress. But I am not able to devise anything analogous to it in my case.

Maybe what I am trying to achieve is programmtically not possible. If its not possible then suggest me a workaround or a completely new approach. If some details are pending you can mention them. Sorry for my ignorance this is my first post here. I welcome you to point out my mistakes.

EDIT:

Database outline:

The URL(s) and keyword(s) are first entered by user which are stored in a database table called link_master and keyword_master respectively. Then keywords are extracted from all the links present in this table and compared with keywords entered by user and their frequency is calculated which is the final result. And the results are stored in another table called link_result. Now sub-links are extracted from the domain links and stored in a table called sub_link_master. Now again the keywords are extracted from these sub-links and the corresponding results are stored in a table called sub_link_result.

The number of records cannot be defined beforehand as the number of links on any web page can be different. Only the cardinality of link_result table can be known which will be equal to multiplication of number of keyword(s) and URL(s) .

I insert multiple records at a time using this resource.

Controller outline:

The controller extracts keywords from a web page and also extracts keywords from all the links present on that page. There is a method called crawlLink. I used Rolling Curl to extract keywords and web page content. It has callback function which I used for extracting keywords alongwith generating results and extracting valid sub-links. There is a insertResult method which stores results for links and sub-links in the respective tables.

Yes, the processing depends on the number of records. The more the number of records, the more time it takes to execute:

Consider this scenario:

Number of Domain Links = 1

Number of Keywords = 3

Number of Domain Links Result generated = 3 (3 x 1 as described in the question)

Number of Sub Links generated = 41

Number of Sub Links Result = 117 (41 x 3 = 123 but some links are not valid or searchable)

Approximate time taken for above process to complete = 55 seconds.

The above result is for a single link. I want to track the progress of the above results getting stored in database. When all results are stored, the task is complete. If results are getting stored, the task is In Progress. I am not clear how can I track this progress.

答:
There are three ways to monitor the progress on a PHP task running on the server.

Use WebSockets To Monitor In Real-Time

Likely overkill for a 55 second task.

Using Ratchet you can create a socket service that you can connect to via Javascript, and have PHP send data in real-time to the browser. The socket connection is keep alive for as long as the Javascript socket is connected.

Timed AJAX Calls

You call pull the server on a regular interval to receive data about the process of the current task (this is what I do all the time). The request would return a JSON response with the current progress.

```<code>$.ajax({url: "/monitor_task?task_id=3"}).done(function(data) { alert(data); });
</code>```

Sharing Progress Data

There are two ways to have your task share it's progress on the server side.

Write the progress to a database table, and have your monitor_task action read that value.

Use a shared memory object (just like a file), and have your monitor_task read that file.

Refreshing The Current Page

Create a view that shows the current progress, and place a meta refresh with an interval. This will tell the browser to always refresh the page for the interval.

```<code><meta http-equiv="refresh" content="5" />
</code>```

Body:
There are three ways to monitor the progress on a PHP task running on the server.

Use WebSockets To Monitor In Real-Time

Likely overkill for a 55 second task.

Using Ratchet you can create a socket service that you can connect to via Javascript, and have PHP send data in real-time to the browser. The socket connection is keep alive for as long as the Javascript socket is connected.

Timed AJAX Calls

You call pull the server on a regular interval to receive data about the process of the current task (this is what I do all the time). The request would return a JSON response with the current progress.

$.ajax({url: "/monitor_task?task_id=3"}).done(function(data) { alert(data); });

Sharing Progress Data

There are two ways to have your task share it's progress on the server side.

Write the progress to a database table, and have your monitor_task action read that value.

Use a shared memory object (just like a file), and have your monitor_task read that file.

Refreshing The Current Page

Create a view that shows the current progress, and place a meta refresh with an interval. This will tell the browser to always refresh the page for the interval.

<meta http-equiv="refresh" content="5" />


问:
Is there a term for reusing code by retyping it?
I built a prototype ("one to throw away") a while ago, and I'm rebuilding it now as an alpha.  My goodness, it's been worth it.

I reused some of the prototype code by copy-pasting then modifying it, but I've fallen into a pattern of looking at the prototype for guidance, but writing the new code from scratch.  This doesn't take too long for me because I'm a pretty fast touch-typist.

Right now I'm rebuilding a complex function, and I'm actually reading it line-by-line and typing equivalent code into my alpha version.  I find it's better than copy-paste-refactor because I get reacquainted with the logic, and I don't miss parts of the code when I'm reading it.  Is there a name for this kind of reuse?  Any authoritative commentary on its benefits/drawbacks?

答:
I would call it implementation where basically your prototype acts as the design.

I often do the same, make a prototype and when useful implement that. What I do though is copy the relevant pieces of the source from the prototype, put it in my main source as comment and work from there.


答:
Productivity. Is there any other justification that makes sense? For me, a well-designed IDE that centralizes a lot of the functions that I perform while programming -- creating and editing code, using source control, debugging, interacting with project management tools, communicating with other programmers, creating documentation, running automated tests -- dramatically reduces the process friction that reduces my productivity.

Additionally, even though I feel as though I need to know how to use each tool individually, I don't want to have to. For me at least, a right-mouse-click is infinitely preferable to opening a CLI and typing.

I have used many, but the IDEs that I return to over-and-over are Visual Studio, Wing IDE and NetBeans. All add significant value to the time that I spend programming.

Title: What justifies the use of an IDE versus a standard editor?

Body:
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?


答:
High quality code is typically supposed to be readable, in the sense that reading it is sufficient to understand and (re)use.

Given that your case is rather opposite, it looks like of one the "write-only" variety, in the sense as this term is used in Wikipedia article Write-only language:

In computer humor, a write-only language is a programming language with syntax (or semantics) sufficiently dense and bizarre that any routine of significant size is too difficult to understand by other programmers and cannot be safely edited. Likewise, write-only code is source code so arcane, complex, or ill-structured that it cannot be reliably modified or even comprehended by anyone with the possible exception of the author...

To avoid misunderstanding, above doesn't really prohibit justified compromises. For example, readability can be compromised when performance consideration force that, or code quality can be compromised in favor of fast prototyping / proof of concept development (like it probably was in your case).

Title: Is there a term for reusing code by retyping it?

Body:
I built a prototype ("one to throw away") a while ago, and I'm rebuilding it now as an alpha.  My goodness, it's been worth it.

I reused some of the prototype code by copy-pasting then modifying it, but I've fallen into a pattern of looking at the prototype for guidance, but writing the new code from scratch.  This doesn't take too long for me because I'm a pretty fast touch-typist.

Right now I'm rebuilding a complex function, and I'm actually reading it line-by-line and typing equivalent code into my alpha version.  I find it's better than copy-paste-refactor because I get reacquainted with the logic, and I don't miss parts of the code when I'm reading it.  Is there a name for this kind of reuse?  Any authoritative commentary on its benefits/drawbacks?


答:
IMHO the term that matches your activity best is just a  rewrite.

This may sound trivial, but some commenters have already used that term, and if you search for the term here on PSE, you will find lots of postings dealing with the question when a rewrite is good or bad, or when you go better with refactoring (which is most times used in opposition to "rewriting" things). See, for example, here:

When is a BIG Rewrite the answer?


问:
Progressbar patterns (Eclipse)
I've struggled quite a bit with Eclipse and progress-monitors to try to have good progressbars which report useful progress information to the user. Inevitably the code gets cluttered with lots of things like

```<code>if (monitor.isCancelled())
    return;

...

lengthyMethodCall(monitor.newChild(10));
</code>```

and all over the place I need to pass a IProgressMonitor as an argument to my methods. This is bad, for several reasons:

The code gets cluttered with lots of code which is not relevant to what the function actually does.

I need to manually guesstimate which parts of the code takes time, and which parts do not.

It interacts badly with automated tests; where much of the information which goes into a progressbar instead should be logged for later inspection.

Is there a way out of this? Are there tools which can help me out with one or more of these problems? Should I be looking at Aspect-Oriented Programming tools, or are there other alternatives?

答:
maybe you could annotate each method with custom annotation and then process those annotations.

or maybe you could log the last execution time of those methods and then estimate time based on that.

Title: Progressbar patterns (Eclipse)


问:
What to do when you're faced with a problem that you can't solve quickly?
I'm a beginner learning Java and after reading the docs I'm trying to solve some of the problems at codingbat.com. Some I managed to solve pretty quickly in a matter of seconds but some not quite. The problems themselves are easy (example http://codingbat.com/prob/p126212) but I sometimes have a hard time finding the solutions. In part because I think of the best possible solution and automatically discard the ones that might work but aren't so elegant and in part because I can't find the right algorithm. This is either due to my inexperience (I have used PHP for web development for about 2 months so I'm not a total beginner - even worked with one framework to build a website) or due to my inability to think of a good algorithm.

I normally don't look at the solutions. I sometimes get stuck even for 1 1/5 hours at simple problems and some of them I eventually solve but some I can't so I eventually look at the solution.

Is it normal/good/bad to concentrate this long if I find a problem I can't solve? I might overreact but should this be so hard for me? Is there such thing as not being able to think of algorithms even with much learning and reading?

Thank you all in advance.

答:
The most important thing in software development is working software. This is especially so in commercial development.

A lot of people spend far too much time trying to be clever or come up with a supposed "elegant" solution when what they should be doing is producing working code.

What you should be doing is solving the problem as quickly as possible. Once you have proven your solution works, then is the time to refactor to make it elegant, fast, etc, if required. Often, once you have working code in front of you it becomes easier to see the more elegant solution.

OwnerDisplayName: Mash


问:
How to use unit testing?
How to use unit testing?

There are a lot of frameworks for different languages, which provide functionality of unit testing. There is a lot of information on how to use each of them technically. Just like "import to your project this lib, type assert, compile, run and blah-blah-blah". And it all is easy to learn.

The place I’m confused in is how to get it: which test to write, to cover large amount of possible bugs?

For example, assume we use jasmine framework for JS, and we are to test email validation function.

Great. Our simple code will look like this:

```<code>describe("Email validation test", function() {
  it("isEmailValid(\"mytestname@gmail.com\") should be true", function() {
    expect(isEmailValid("mytestname@gmail.com")).toBe(true);
  });
});
</code>```

But actually we have no ideas how does isEmailValid function is written and where can it fail. Maybe it works only if we have gmail.com domain? So we should include another one test with any other domain.

Or maybe it doesn't work if we have some very specific domain, just like "warhammerhobbitbanachspace.am"? In that case it would be rather difficult to catch a bug. Or, even, impossible.

Or maybe it'll fail if we have more than 42 symbols in the string with email? Or maybe it'll fail if we have exactly 9 symbols?
And that is only a little amount of examples of places which it would be useful to test. And that is just a simple string validation function...
And how can we really test some complex objects then? Yeah, I know, it is impossible to test everything. But how then to choose what really should be tested, and what not?

Are there any books or articles, which explain ... some patterns/techniques/principals of covering the code with useful tests?

答:
What you seem to be looking for is the concept of test coverage, or more specifically for unit testing, code coverage.

There are many ways you can measure how well your tests cover the code, from the very high level e.g. you could say your isEmailValid function produces two possible outputs :. all inputs can be partitioned into two equivalence classes and you can get full coverage of those classes by testing a single member of each.

But at unit test you more likely want to look at a more low level measure such as statement coverage, which would allow you to see that you have tested every statement within the function, not just each observable output

Title: How to use unit testing?