问:
Identity matrix using Fortran 95
The following code give the identity matrix of any size the user wish it to be:

```<code>program identitymatrix

  real, dimension(:, :), allocatable :: I
  character:: fmt*8
  integer :: ms, j

 print*,'the size of the matrix is?'
 read*,ms

  allocate(I(ms,ms))
  I = 0                           ! Initialize the array.
  forall(j = 1:ms) I(j,j) = 1     ! Set the diagonal.

  ! I is the identity matrix, let's show it:

  write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'
  ! if you consider to have used the (row, col) convention,
  ! the following will print the transposed matrix (col, row)
  ! but I' = I, so it's not important here
  write (*, fmt) I(:,:)

  deallocate(I)

end program identitymatrix     (the end of the code )
</code>```

I am a bit confused about these two code  pieces ?

```<code>write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'

write (*, fmt) I(:,:)
</code>```

What does (A,I2,A) do exactly?

答:
'(A,I2,A)' is a format specification; this one specifies a character field of sufficient length to hold the variable passed to it, followed by a 2-digit integer (field), followed by another character field which will be as long as the variable passed.

This statement

```<code>write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'
</code>```

uses that format specification to write another format specification into the character variable fmt.  If, at run-time, ms has the value 4, fmt will become '(4F6.2)'. This, in turn, is used to format the next write statement:

```<code>write (*, fmt) I(:,:)
</code>```

This is the standard Fortran approach to creating output formats at run-time.

Title: Identity matrix using Fortran 95

Body:
'(A,I2,A)' is a format specification; this one specifies a character field of sufficient length to hold the variable passed to it, followed by a 2-digit integer (field), followed by another character field which will be as long as the variable passed.

This statement

write (fmt, '(A,I2,A)') '(', ms, 'F6.2)'

uses that format specification to write another format specification into the character variable fmt.  If, at run-time, ms has the value 4, fmt will become '(4F6.2)'. This, in turn, is used to format the next write statement:

write (*, fmt) I(:,:)

This is the standard Fortran approach to creating output formats at run-time.


问:
Is there a problem holding large numbers of open socket connections for lengthy periods of time?
The application we have in mind is a relay server. The aim is to accept large numbers of incoming socket connections (at least thousands) that will stay open for lengthy periods (hours or maybe days). They will exchange modest quantities of data and they need reasonably low latency.

The technical design is straightfoward and we have a test implementation. Our preference is to use Windows hosting and .NET, because that's the technology we know. However, this kind of usage is well outside what we are familiar with.

The question is whether there are specific limits or constraints to be aware of that are inherent in or common to software that does this, and that we should allow for in our design and/or test for before a roll-out.

I found this question (Handling large amounts of sockets) and this link (http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1), which tend to suggest that our solution should work.

--

Commenters have suggested opening and closing ports, or using some kind of protocol, without suggesting how. The problem is that at any time a message might be relayed to an individual known destination with the expectation that it be received quickly (say 1 second at most, preferably sooner). The destination is (in general) behind a firewall with unknown properties, so cannot (in general) run a server or accept incoming connections. It can only make outgoing connections. We think it needs a persistent outgoing connection in order to receive packets at any time without notice. Alternative suggestions would be of interest, although strictly off topic for this question.

Other commenters have suggested there are OS limits, but not specified any. Assuming that this is some version of Windows server and some (perhaps large) amount of memory, are the limits likely to be a problem? Roughly what will they be? Is Windows a bad idea?

答:
I worked on a relay server for stock market data in C# on a Windows Server. There was no way I could get thousands of simultaneous connections relayed by one machine. The specs for the relay were very simple 1 connection to stock market data provider, and unlimited outbound connects to SilverLight clients.

There are two basic approaches that I investigated.

Use a thread pool, each client gets a socket and worker thread.

Use a worker thread, worker thread pushes data by iterating over all open sockets.

Neither approach could exceed the performance limits of the CPU, and each approach had serious limitations and restrictions.

Using a thread pool.

Windows sucks at multi-thread handling. Once I hit around 250 threads things just started to go down hill. It isn't a memory or system resource problem. It's a quantity problem. While Windows has no problem managing 250 threads. It's another story asking Windows to keep those 250 threads busy relaying data. As performance lags a data backlog starts to happen.

Using a worker thread.

You can't use a worker thread to iterate sockets if those sockets are blocking. Each time the thread hits a socket that has to timeout all other sockets are left waiting. If you switch to asycn socket operations, then a huge backlog of callbacks are generated to quickly and everything breaks.

For me the results were.

100 clients everything is stable.
250 clients everything is working but limit reached.
1000 clients never achieved.

Conclusion.

C# on Windows is not the right tool for a socket relay server. Not for client connections ranging in the thousands.

The only alternative is to not use HTTP sockets, and switch to a broadcasting protocol like UDP or TCP. For me this was not an option as no data was allowed to be dropped. Most broadcasting protocols assume packet loss is acceptable.

Finally.

If you are able to create a C# relay that can handle thousands of clients. Please come back and let me know how you did it.

ContentLicense: CC BY-SA 3.0


问:
Colons in internationalized UI
When using gettext or a similar framework, should the translation strings include ':' (like "Label:") for generating labels for UI or should I add ':' in UI code itself?

答:
When I was doing my own internationalisation a few years ago, it worked something like this:

Messages in the source code were written in English

Messages were translated at runtime by applying a translation (which appeared in the source as translate("string") or more usually /"string"). There was expected to be a pre-built dictionary of messages and translations.

When translating a message, white space at each end was trimmed, and trailing punctuation was removed, as was any capitalisation. After translating what was left, these were put back.

To provide more context, I sometimes added a comment to the string, which was part of the translation process to help find the best match, but the comment was then discarded.

So, with a message such as " Disk: ", the string "disk" was translated into, say, "disquette", and then recomposed as " Disquette: ". This reduced the number of very similar messages.

I only did this for a small number of western European languages; probably there would be problems with more exotic ones. However I was using a scripting-type language for this so some string processing could be used for whatever problems came up: when I needed to translate "G" (short for Green), it appeared in the source as left(/"Green"), translated to something like "vert" and reduced to "V".

However I'm not familiar with current frameworks and how they might work; don't they provide any guidelines for dealing with these types of issues?

Title: Colons in internationalized UI


问:
Necessity of Interfaces for Small Projects
Is it necessary to use interfaces for small projects? I work at a shop writing small custom applications for clients, primarily data manipulation. I'm mostly self-taught but also took some programming classes in college. I've been trying to apply more OO concepts to my coding practices, but I really don't see the need for interfaces in the work that I do. My largest project so far had around 10 classes in it.

Are interfaces necessary for small projects/applications or only for large-scale software systems?

EDIT: This is not a duplicate. I'm asking about using interfaces in general for small projects, not using an interface for when there is only a single implementation...

答:
Short answer: No.

Long answer: There's a trade-off between using a class and an interface. Interface implementations can be swapped at runtime. That's nice because it's flexible - but it also means someone can code up a bad IFoo and pass it to one of your functions that otherwise works fine. With a concrete (and sealed/final) Foo there's only one implementation, so if you get it right, it always works.

Another drawback of interfaces is that they can't inspect the implementation details of other members of that interface. Foo methods can inspect the private variables of other Foos, but IFoos can only look at the interface of other IFoos. This can limit certain optimizations, so if there's only one implementation of an interface it can hurt you without providing any benefits.

Unfortunately mainstream OOP languages don't provide a way to swap class implementations. Ideally you'd be able to have multiple Foo implementations and pick one of them at compile time. However, with an IDE it's not hard to extract an interface out of a class after the fact.

If you don't need to juggle multiple kinds of Foos in the same program there's no need to add an extra layer of indirection with an interface. Even if you do need multiple kinds of Foos in the same program, you don't necessarily need an interface. You can have an abstract base class with a private constructor and implement a finite number of types of Foos as static final inner subclasses. See also How do you encode Algebraic Data Types in a C or Java-like Language.

Interfaces really shine when you don't want to limit the number of possible implementations usable at runtime at all.

EDIT: For a more thorough explanation of the trade-offs involved, see On Understanding Data Abstraction, Revisited.


问:
Multi-level paging tables
Referring to the image here:

From http://en.wikipedia.org/wiki/File:X86_Paging_4K.svg

Could somebody please explain something for me? I don't get exactly how this works. As I understand it the page "directory" contains an entity which essentially points to the beginning of the "page table". However, surely all of the entities in the page "directory" would contain the exact same value? Or, does this mean we have 1x page "directory" but N page "tables" (at the same level in the page multi-level hierarchy")?

If there are N page "tables" and one page "directory" I get why the PD would point to one of the N PTs. If there aren't then I am really confused.

答:
N page tables.

If you look at the Wikipedia entry for Page Tables, you'll see two diagrams there; one for the two-level page table structure, and one for the three-level page table structure.  The purpose of the three-level page table structure is to implement PAE, which allows memory access beyond 4GB.

Title: Multi-level paging tables


问:
Does functional programming add complexity in code?
For the entire past year I've been written Scala code (coming from a Java background). I really liked how you could create simpler and cleaner code, with vals, case classes, map/filter/lambda functions, implicits and the type inference. I've used it mostly for an Akka-based application.

This year I'm on a Scala project with a new team, who really like functional programming. They heavily use Scalaz, and the code is filled everywhere with applicatives, context bounds, reader/writer/state monad, even the main method is "wrapped" in an I/O monad. Their reasoning is that this makes the compiler "work for us" in asserting that the code is correct, and each function is free from side effects.

Even so, from my point of view all this syntax really gets in the way of the business logic. For instance, a type of "MyBusinessObject" is fine, as well are types like "List[MyBusinessObject]", "Option[MyBusinessObject]" or even "Future[MyBusinessObject]". They all have a clear meaning and purpose. On the other hand, code like:

```<code>def method[M[_]: Applicative] = {
  case (a, b) => (ca[M](a) |@| cb[M](b)) {
    case t @ (ra, rb) =>
      if (ra.result && rb.result) t.right
      else t.left
  }
}
</code>```

does it add complexity to the program, or is it just me that I'm not used to this way of programming?

答:
I would argue that in general functional programming reduces complexity by eliminating mutable state, thereby reducing the number of cases that must be considered when trying to understand how a section of code works.

However, functional programming makes higher degrees of abstraction possible, and while highly abstract code can be extremely useful it can also be difficult to understand because it is by definition divorced from the context which you would ordinarily use to guide your understanding.  Your comment "They all have a clear meaning and purpose" about business objects is undoubtedly true, but is really a reflection of the fact that that logic is very specific to a need and context you already understand.  The existence of a construct like Monad allows you to make something very useful with little effort, but the web is littered with pages trying to explain what a Monad is.  That's abstraction for you.

Also, Scalaz was written by folks who had been eating and breathing FP for a long time; they wanted to bring functionality available in Haskell to Scala.  In doing so they made no attempt to be pedagogical.  Scalaz makes use of a vocabulary and style which seem clear and straightforward to the authors but alien to the uninitiated.  Methods which are puzzling to the rest of us seemed so obvious to the authors, given their Haskell background, that they didn't even warrant a comment.

Furthermore, as a functional programming language Scala has some shortcomings (in part because the JVM has shortcomings) that forced the Scalaz authors to write uglier code in some cases.  For example, the lack of general tail call elimination forces the use of trampolines in some code, and the lack of a "kind system" can complicate type signatures.

And finally, Scalaz makes great use of itself.  That could be thought of as a sign of its power, but for the uninitiated it can make the source a puzzle -- any random piece of code you look at is likely to make use of something else that looks alien to you.

Hang in there.  And this might help.


问:
What is the best way for an experienced developer to work on a WordPress blog
I'm beginning to work on my first WordPress blog, however I've noticed most tutorials just have you do modifications (such as theme changes, installing plugins) on the production site. This worries me for a few reasons:

No backups

No version control

If you make a mistake, your production site is affected

Developing remotely is slower than local development, especially when tweaking css files.

I understand why WordPress works like this - it allows people with no development experience to manage their WordPress installation (or the one provided by their service provider). It also allows you to work on the WordPress installation without having ssh access to the server. However as I am confortable working with tools like git and ssh, and am using a virtual server for the blog, this isn't very important to me.

So I was wondering what techniques experienced developers use when working on a WordPress blog. For example:

Do you develop locally, then push the changes to the live site? How do you do this?

How do you manage database changes and backups?

What do you store under version control (if anything)?

If a plugin changes the database, do you somehow track the changes it does in version control, so you can rollback the changes done by the plugin if you need to?

Or maybe I'm just overcomplicating everything if working on the production site isn't as risky as I am thinking it would be. I would appreciate any answers either way.

答:
I've been working with Wordpress for 5 years. My short answer to "What is the best way for an experienced developer to work on a Wordpress blog?" is to change the approach depending on the project.

If your dealing with your own sites I recommend taking them offline for a short period. Install the plugin straight to the live site and give it a checkup. Ensure there are no conflicts or unusual behavior. Obviously you do this with plugins that can be trusted. Local testing is only worth doing if everything is duplicated and that is time consuming.

I've known developers to download a clients entire website, files and data. Just to do a small amount of work. What is worse, they don't ask for permission to backup the entire site locally. Freelancers do this a lot the moment the customer gives FTP access. It's habit and some would say it is procedure.


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答: Code beautification like unscrutify will be able to solve some of your problems. If you are ready to pay for this then there are high level softwares which embed the rules in the source code itself like Parasoft. Parasoft makes it compulsory to write the code in uniform style. You can embed your own rules too. When such tools are used the developers are forced to use uniform style. And after a while they will get used to it.  </p>

ContentLicense: CC BY-SA 2.5


问:
Appending local MySQL data to same MySQL data in web server
my IT boss wanted this scenario to be undertaken: First, we develop an Alumni program using PHP and deploy this in the web server which can be accessed by that school alumni in the web to update their personal data anytime. Then, using exactly that SAME program we must also deploy this locally, thru the LAN in its satellite campus which is far and have a very erratic and unreliable internet connection. The purpose is that that the latter system (in LAN) can still be used to add new alumni data even during "offline" periods, and then, once the internet signal is OK, or now being "online" to just upload these offline-generated data in MySQL to the web server hosting THE SAME software program. How do we do a seamless data transfer then of this MySQL database - from the LAN to the web server - once the online signal is now steady?
Thanks for any advice...</p>

答:
A good start might be to look at MySQL replication.

Replication enables data from one MySQL database server (the master)
  to be replicated to one or more MySQL database servers (the slaves).
  Replication is asynchronous - slaves need not be connected permanently
  to receive updates from the master. This means that updates can occur
  over long-distance connections and even over temporary or intermittent
  connections such as a dial-up service. Depending on the configuration,
  you can replicate all databases, selected databases, or even selected
  tables within a database.

For more info, see https://dev.mysql.com/doc/refman/5.0/en/replication.html


答:
I've finally decided to use entire strings (strings with colons in this case) in my i18n files.

The reason for this that in French there should be a space before colon. So the best way to encode French is to put colons (with spaces before) in translation strings.

No, we do not translate to French. But this is an example for a general rule of behavior: Put colons in translation strings, not in UI code.

Title: Colons in internationalized UI

Body: When using gettext or a similar framework, should the translation strings include ':' (like "Label:") for generating labels for UI or should I add ':' in UI code itself?


答:
Even if you only have a small project, if you want to have unit tests, you'll probably want to use interfaces for your services and dependencies.  That way you can inject mock implementations of those in your unit tests.

If you're not doing unit testing, then there are other common uses for interfaces, such as the strategy pattern.

Title: Necessity of Interfaces for Small Projects

Body:
Is it necessary to use interfaces for small projects? I work at a shop writing small custom applications for clients, primarily data manipulation. I'm mostly self-taught but also took some programming classes in college. I've been trying to apply more OO concepts to my coding practices, but I really don't see the need for interfaces in the work that I do. My largest project so far had around 10 classes in it.

Are interfaces necessary for small projects/applications or only for large-scale software systems?

EDIT: This is not a duplicate. I'm asking about using interfaces in general for small projects, not using an interface for when there is only a single implementation...


答:
The colon can be regarded as a punctuation symbol. It is a convention which is part of the text, just like a period or question mark.

We wouldn't leave out the question mark from "Are you sure you wish to exit?" and then write code to add the question attributes in a language-dependent manner to the translated string. Doing so means that the UI code is unnecessarily taking on the responsibilities of knowing how to punctuate sentences in various languages: a responsibility which can be handled in the message substitution.

There is an intermediate possibility. It is likely that, just like all labels have the colon feature in English, in other languages labels also have some lexical element in common. That element, if present, is probably some kind of prefix or suffix, or both.

You could represent the labels without the adornment, and then have an additional translatable string which provides a schema for adding the label adornment. As an example, suppose that C sprintf style formatting is available in the UI application. The English version of the label-generating format string would be "%s:", and that could be the default as well, since it works in some other languages. The UI translators can replace this "%s:" with whatever they see fit. One of the possibilities is that they can replace it with just "%s" (do nothing) and then specify the full, adorned representation of each label in the translated string table. So this approach even handles some strange possibilities where the lexical marker which denotes a label has to be inserted into the middle.

This approach doesn't seem worthwhile, if all it achieves is a slight compression in the representation of label strings: the removal of one colon character.  If you have to write 100 characters of extra code for this, you have to remove colons from 100 labels just to break even: and that doesn't even take into consideration justifying the time spent.

There has to be some payoff for this: namely that the application uses the strings for purposes other than just generating labels, such as generating sentences which refer to the UI fields by name. Say that a dialog box has a "User ID:" label for entering text. If you have generic logic which produces the message "You have entered an invalid user ID." by combining a sentence boilerplate text with the name of a UI element, then it's necessary to have the unadorned string "user ID", and pass it through a label-making function to generate "User ID:".

Title: Colons in internationalized UI


问:
Does design by contract imply correct output?
Design by Contract says, in terms of the function talking: "you give me all the right parameters and I'll give you exactly this kind of data" ...in essence.

So, given that, should I use up resources checking the output?  I should check for properties that the function does not guarantee its output possesses, but the properties the function guarantees need not be checked, right?

Here's an example:

```<code>class Transition_Manager {
    string str = generate_non_null_string();
    process_using_a_function_that_can't_handle_null_strings( str );
}
</code>```

答:
if you take information from untrusted sources (network, user) then you should check it all

that said that said binary search would never be able to work without the (unchecked) assumption of the array being sorted. if you checked sorted-ness then you might as well do a linear search.

most important is being able to fail gracefully if you do get wrong data, debugging is much easier when there is a nice exception and related log to look at.


答:
define "necessary"

if two classes must implement the same interface in order to be interchangeably used by some object, then using an interface is technically necessary - though inheriting from a common base class can get around this (for languages that don't support interfaces, for example)

the size of the project is irrelevant


答:
Consider validating the output of your function before runtime.

You can do this by writing unit tests that validate the output of your function for all the known valid inputs (or maybe just a representative subset of valid inputs if the full set is too large).

This offsets the cost of data validation from your application to your development process.

This works particularly well if you have something like a Continuous Integration server set up to automatically run your tests.

Title: Does design by contract imply correct output?

Body:
Design by Contract says, in terms of the function talking: "you give me all the right parameters and I'll give you exactly this kind of data" ...in essence.

So, given that, should I use up resources checking the output?  I should check for properties that the function does not guarantee its output possesses, but the properties the function guarantees need not be checked, right?

Here's an example:

```<code>class Transition_Manager {
    string str = generate_non_null_string();
    process_using_a_function_that_can't_handle_null_strings( str );
}
</code>```


问:
Are there flavours of OOP where some or all of the SOLID principles are antithetical to clean code?
I recently had a discussion with a friend of mine about OOP in video game development.

I was explaining the architecture of one of my games which, to my friend's surprise, contained many small classes and several abstraction layers.  I argued that this was the result of me focusing on giving everything a Single Responsibility and also to loosen the coupling between components.

His concern was that the large number of classes would translate to a maintenance nightmare.  My view was that it would have the exact opposite effect.  We proceeded to discuss this for what seemed like centuries, eventually agreeing to disagree, saying that perhaps there were cases where SOLID principles and proper OOP didn't actually mix well.

Even the Wikipedia entry on SOLID principles states that they're guidelines that help to writing maintainable code and that they are part of an overall strategy of agile and adaptive programming.

So, my question is:

Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

I can imagine right away that the Liskov Substitution Principle could possibly conflict with another flavour of safe inheritance.  That is to say, if someone devised another useful pattern implemented through inheritance, it is quite possible the LSP might be in direct conflict with it.

Are there others?  Perhaps certain types of projects or certain target platforms work better with a less SOLID approach?

Edit:

I'd just like to specify that I'm not asking how to improve my code ;)  The only reason I mentioned a project in this question was to give a little context.  My question is about OOP and design principles in general.

If you're curious about my project, see this.

Edit 2:

I imagined this question would be answered in one of 3 ways:

Yes, there exist OOP design principles which partially conflict with SOLID

Yes, there exist OOP design principles which completely conflict with SOLID

No, SOLID is the bee's knees and OOP will forever be better with it.  But, as with everything, it's not a panacea.  Drink responsibly.

Options 1 and 2 would have likely generated long and interesting answers.  Option 3, on the other hand, would be a short, uninteresting, but overall reassuring, answer.

We seem to be converging onto option 3.

答:
In my early developing days, I began to write a Roguelike in C++. As I wanted to apply the good object-oriented methodology I learned from my education, I immediately saw the game items as being C++ objects. Potion, Swords, Food, Axe, Javelins etc. all derived from a basic core Item code, handling name, icon, weight, that kind of stuff.

Then, I coded bag logic, and faced a problem. I can put Items in the bag, but then, if I pick one, how do I know if it's a Potion or a Sword ? I looked up on the Internet how to downcast items. I hacked the compiler options to enable runtime information so I would know what my abstracted Item true types are, and started switch logic on types to know what operations I would allow (e.g avoid drinking Swords and put on Potions on my feet)

It essentially turned the code in a big ball of half-copypasted mud. As project went on, I started to understand what was the design failure. What happened is that I've tried to use classes to represent values. My class hierarchy wasn't a meaningful abstraction. What i should have done is making Item implement a set of functions, such as Equip (), Apply (), and Throw (), and make each behave based on values. Using enums to represent equip slots. Using enums to represent different weapon kinds. Using more values and less classing, because my sub-classing had no other purpose than to fill these final values.

Since you are facing object multiplication under an abstraction layer, I think my insight can be valuable here. If you seem to have too many object types, it may be that you are confusing what should be types with what should be values.


答:
Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

In general, no. History has shown that the SOLID principles all largely contribute to increased decoupling, which in turn has been shown to increase flexibility in code and thus your ability to be accommodating of change as well as making the code easier to reason about, test, reuse...  in short, make your code cleaner.

Now, there can be cases where the SOLID principles collide with DRY (don't repeat yourself), KISS (keep it simple stupid) or other principles of good OO design. And of course, they can collide with the reality of requirements, the limitations of humans, the limitations of our programming languages, other obstacles.

In short, SOLID principles will always lend themselves to clean code, but in some scenarios they'll lend themselves less than conflicting alternatives. They're always good, but sometimes other things are more good.

Title: Are there flavours of OOP where some or all of the SOLID principles are antithetical to clean code?

Body:
I recently had a discussion with a friend of mine about OOP in video game development.

I was explaining the architecture of one of my games which, to my friend's surprise, contained many small classes and several abstraction layers.  I argued that this was the result of me focusing on giving everything a Single Responsibility and also to loosen the coupling between components.

His concern was that the large number of classes would translate to a maintenance nightmare.  My view was that it would have the exact opposite effect.  We proceeded to discuss this for what seemed like centuries, eventually agreeing to disagree, saying that perhaps there were cases where SOLID principles and proper OOP didn't actually mix well.

Even the Wikipedia entry on SOLID principles states that they're guidelines that help to writing maintainable code and that they are part of an overall strategy of agile and adaptive programming.

So, my question is:

Are there cases in OOP where some or all of the SOLID principles do not lend themselves to clean code?

I can imagine right away that the Liskov Substitution Principle could possibly conflict with another flavour of safe inheritance.  That is to say, if someone devised another useful pattern implemented through inheritance, it is quite possible the LSP might be in direct conflict with it.

Are there others?  Perhaps certain types of projects or certain target platforms work better with a less SOLID approach?

Edit:

I'd just like to specify that I'm not asking how to improve my code ;)  The only reason I mentioned a project in this question was to give a little context.  My question is about OOP and design principles in general.

If you're curious about my project, see this.

Edit 2:

I imagined this question would be answered in one of 3 ways:

Yes, there exist OOP design principles which partially conflict with SOLID

Yes, there exist OOP design principles which completely conflict with SOLID

No, SOLID is the bee's knees and OOP will forever be better with it.  But, as with everything, it's not a panacea.  Drink responsibly.

Options 1 and 2 would have likely generated long and interesting answers.  Option 3, on the other hand, would be a short, uninteresting, but overall reassuring, answer.

We seem to be converging onto option 3.


问:
Can a Java interface declaration enforce parameter properties?
As far as I know, declaring an interface is like so:

```<code>public interface Roots_Squares {
    public double square_root( double value );
}
</code>```

Now... how do you enforce value to have non-negative values?  Such a function should avoid negative values right?  If someone creates a class that implements this, and that implementation does not handle negative values, and then I use their class with a negative value... well, things break.

It then becomes my responsibility to check for negatives when I'm pretty sure the implementor should do the checking.

答: As explained a bit more thoroughly in this answer, that's (part of the) price you pay for an interface. If you want to be able to use new implementations of your abstraction at any time, you have no way of forcing those implementations to be correct.</p>


问:
Correct way to undo the past few git commits including a merge?
My team is working with git for the first time and has really messed up our git remote due to our inexperience. I'm trying to help educate them on git to solve the problem in the long term, but in the meantime, the commits that have been made are totally wrong. We haven't made very much progress at all, and I don't see the value in retaining these commits when they could cause confusion/additional problems down the line.

The most recent commit was a merge between the master branch and a second branch that one of the team members unintentionally created. If I try to revert, git states that I must be using the -m flag, but I'm not sure whether I should be reverting or trying to rebase in this case, or how I would do it given the structure of the past couple of commits.

What is the best way to resolve this issue and how should I go about doing it?

答:
I believe you're looking for the git reset command. If you run git log it will show you a commit history for your repo. Then run git reset --hard HEAD-number of commits you'd like to go back.

Documentation here: http://git-scm.com/docs/git-reset


答:
To undo the merge, you can do

```<code>git checkout master
git revert -m 1 [SHA of the merge commit]
git push
</code>```

This will create and push a new commit which reverts all changes that were merged in.

It's also possible to alter master's history so that it appears as if the merge never happened, but I wouldn't recommend it. Your teammates would have trouble when they try to pull master and the history is different. Also it's easy to revert a revert commit if you reverted the wrong changes, but if you alter mater's history, it's harder to undo that.

Title: Correct way to undo the past few git commits including a merge?

Body:
My team is working with git for the first time and has really messed up our git remote due to our inexperience. I'm trying to help educate them on git to solve the problem in the long term, but in the meantime, the commits that have been made are totally wrong. We haven't made very much progress at all, and I don't see the value in retaining these commits when they could cause confusion/additional problems down the line.

The most recent commit was a merge between the master branch and a second branch that one of the team members unintentionally created. If I try to revert, git states that I must be using the -m flag, but I'm not sure whether I should be reverting or trying to rebase in this case, or how I would do it given the structure of the past couple of commits.

What is the best way to resolve this issue and how should I go about doing it?

Body:
To undo the merge, you can do

git checkout master
git revert -m 1 [SHA of the merge commit]
git push

This will create and push a new commit which reverts all changes that were merged in.

It's also possible to alter master's history so that it appears as if the merge never happened, but I wouldn't recommend it. Your teammates would have trouble when they try to pull master and the history is different. Also it's easy to revert a revert commit if you reverted the wrong changes, but if you alter mater's history, it's harder to undo that.


问:
Should developers "own" the build server(s)?
The build server at our company sucks. The build agents (there are a dozen of them, each is a separate VM, and apparently they are all living on their own ESX server) are SLOW. The web interface is SLOW and is running on a Windows VM, also on ESX. Everything is SLOW, SLOW, SLOW. Artifact upload sometimes fails for unknown reasons. Sometimes the web interface reports in the UI that it has run out of memory and it seizes up then crashes. It seems like IT is rebooting it at least once every day. Today they are rolling back a minor update because it has caused problems.

Currently IT owns the hardware that the build servers run on and we have zero visibility into that. We do have admin control over the software. We (the developers) are constantly complaining about it but nothing seems to really improve. Does it make sense for developers to own the build server(s)? IT doesn't really have as much incentive to make them reliable and fast as developers do. In order to get IT to fix the problems we have to complain to our managers and then they have to talk to their managers who then tell IT to fix it. We can report problems to IT directly but that just doesn't seem to work to get things fixed because IT has lots of other things they need to deal with. Also, the developers are the ones who are actually using the build system and are probably a lot more familiar with it than IT.

How does it work at other companies?

We are about a 150 person company. So probably half of that is engineering, but a third of that is probably hardware, so we have maybe 40 or so devs.

答:
Ideally developers should not have to own the build server or even maintain the build process themselves. Every build in a company should go through common parameterized pipelines that have been defined for building projects at the company. This provides several benefits: First, developers don't have to worry about the build process, a dedicated team maintains it. Second, new changes to the pipeline can benefit everyone at once, rather than having to roll it out to dozens of individual build processes. Lastly, it allows the organization to derive powerful metrics about the quality of their builds across the board.

This isn't a pipe dream; we actually do this at my company. 300 engineers build several hundred projects in the same pipeline on a regular basis, and we sometimes have thousands of runs through the pipeline in a single day, all building and automatically deploying to production. It works amazingly well, because we have a strong emphasis on Continuous Delivery principles, as espoused by the canonical book on the subject.

My organization didn't arrive there overnight. It required buy-in from executives at the top. We were at the same point as most people about two years ago: Individual builds for projects and manual configuration and deployment to environments. Following principles of Continuous Delivery has yielded enormous benefits for developers.

So, like I said, in my mind that's the ideal builds and deployments strategy. But it sounds like your IT department hasn't bought into the concept of providing quality build systems and processes yet. If you can't get support from your IT dept., then my suggestion would be to try to roll your own process for now with your own build servers if you have the organizational freedom to do so. Leaving IT to do your own thing is a surprisingly effective way to get them to offer better support to you. :)


问:
Pair Rotation in a team for effective pair programming
We follow pair programming in our company and always face the issue of balanced and effective pair rotation within the developers on stories.

We follow a simple metrics in which every developer's name is mapped with every other developer and we mark the respective intersection whenever two developers are pairing.

This is not working out well, we cannot track how much time a pair has spent pairing and people forget to update the metrics many times. Tracking the pair rotation is helpful because we want the project knowledge to be shared across the team, and not just one pair. So usually what happens is, whoever is pairing keeps pairing till the entire story is completed (given they have better context), and no body else knows about what is being done & if the story or a regression/production bug comes back, the same pair has to pick it up (leaving whatever they are currently doing), which is what creates a bottleneck.

Are there any known metrics that can be used for tracking the pair rotations.

答:
I'm not sure that you want to do this. Your reason for pairing is very good - sharing knowledge across the team, making sure that multiple people are exposed to different parts of the code so you have more people to be able to work in areas. However, the whole idea of timeboxing pairs, especially in the middle of a particular work item (a story, a bug, whatever) doesn't seem like a good idea.

Breaking up a pair in the middle of a story interrupts flow. You have two people who have come together and are working effectively to solve a problem. In the middle of them coming up with a solution, implementing, and testing it, you rip them apart and try to create a new pair. This new pair needs to develop as a team, get on the same page, and then continue with the work - the net result is a disruption to productivity and quality.

I like the idea of creating new pairs, but only when it makes sense. I would advocate pairs working together for a sprint. In order to better spread pairs around, do keep track of who has paired and try to keep new people working together. Of course, if there are people who don't work well together, you may want to avoid that pairing in the future.

Your concerns about needing to interrupt work if there is a regression, a bug, or the story comes back up doesn't make sense to me. That approach of "drop everything to fix an issue" isn't agile. Unless the issue is a showstopping issue, it should be put into the backlog and prioritized and fixed when appropriate. If it is urgent and needs to be immediately addressed, you don't need the same pair to work on it. Assign it to a pair that has someone who has knowledge of that part of the code. This leaves you with one person who understands the functionality along with the design and implementation and someone who can now learn it as they implement the fix.


答:
In the past, I had very positive experiences with having a dedicated build team consisting of just a few developers who reported to the QA department. The build team's builds were the company's gold standard. If your build was broken, they wouldn't accept it. The code that shipped came from their servers only. This provided a lot of incentive for each team to ensure their builds and unit tests were sane. This worked very well in a company of nearly 120 developers and 40 QA all spanning ~15 teams.

In my view, each team is responsible for their own builds but not the build server. Leave the developers to develop! A build team is responsible for the build servers and for collaborating with each respective team to ensure build and test sanity.

You may want to take a "grass roots" approach. If you have the option to set aside your own hardware, I would set up a personal build server and set the example. Once word gets out that you are able to quickly provide successful and repeatable builds, others will want to adopt your strategy. Hopefully, this will encourage buy-in from those who have the power to make the necessary changes.

Title: Should developers "own" the build server(s)?

Body:
The build server at our company sucks. The build agents (there are a dozen of them, each is a separate VM, and apparently they are all living on their own ESX server) are SLOW. The web interface is SLOW and is running on a Windows VM, also on ESX. Everything is SLOW, SLOW, SLOW. Artifact upload sometimes fails for unknown reasons. Sometimes the web interface reports in the UI that it has run out of memory and it seizes up then crashes. It seems like IT is rebooting it at least once every day. Today they are rolling back a minor update because it has caused problems.

Currently IT owns the hardware that the build servers run on and we have zero visibility into that. We do have admin control over the software. We (the developers) are constantly complaining about it but nothing seems to really improve. Does it make sense for developers to own the build server(s)? IT doesn't really have as much incentive to make them reliable and fast as developers do. In order to get IT to fix the problems we have to complain to our managers and then they have to talk to their managers who then tell IT to fix it. We can report problems to IT directly but that just doesn't seem to work to get things fixed because IT has lots of other things they need to deal with. Also, the developers are the ones who are actually using the build system and are probably a lot more familiar with it than IT.

How does it work at other companies?

We are about a 150 person company. So probably half of that is engineering, but a third of that is probably hardware, so we have maybe 40 or so devs.


答:
As an API writer you should validate that the inbound parameters meet your processing criteria before you proceed, regardless of who you think is calling you.

As an API consumer, you should verify that the results meet you processing needs regardless of how safe you think the API is.

When writing code, trust is overrated.


答:
Here's my opinion:

Although SOLID principles aim for a non-redundant and flexible codebase, this might be a  trade-off in readability and maintenance if there are too many classes and layers.

It's especially about the number of abstractions. A large number of classes might be ok if they are based on few abstractions. Since we don't know the size and the specifics of your project, it's hard to tell, but it's a little worrysome that you mention several layers in addition to a large number of classes.

I guess SOLID principles do not disagree with OOP, but it's still possible to write non-clean code adhering to them.


问:
Is it really possible to have libraries not depend on other libraries?
I often see the advice that you should try to make each library independent. And yet in reality I can never seem to achieve this. Is this BS advice or is it actually possibly in any realistic way?

Example: I write a 2D Vector library, I then use that to make a 2D collision library. I then build a 2D physics library that uses both the 2D Vector Library and the 2D Collision library. Am I seriously expected to figure out a way to make the physics library not depend on the other 2 libraries? Likely I'll eventually want to be able to serialize/deserialize the physics and collision data which will mean I'll want to make them further depend on some serialization library.

Another example: I have a string library with lots of string functions (think endsWith(str, ending) and startsWith(str, start) or whatever. I then write a templating library that uses my string library.

I rarely seem to be able to write a new library that doesn't use other libraries.

I could write interfaces and then write adaptors for all of those to attempt to decouple one library from another but it's unlikely to be performant and often the models of the different libraries mean that even if I could decouple with an interface trying to use a different library than the one originally decoupled will end up being impossible or massively non-performant.

So, is that original advice BS or is there some way to actually apply the advice in the real world?

答:
It's entirely possible to build libraries using bare code.  In fact, I'll go out on a limb and say that it's not uncommon to do so.  However...

The history of software is laying abstractions on top of older abstractions.  Once you've figured out how to do a thing, it is customary to wrap that thing in a function, module or library and call it, rather than reinventing the wheel every time.

In this way, you stand on the shoulders of the ones who have come before you. So you can either climb Mount Everest by foot, or get airlifted to the summit by helicopter.  Each approach has its own advantages.


答:
The idea behind that advice is that dependency management sucks on many platforms (keyword: “DLL hell”, although the problem exists in various degrees for all platforms and all languages). This is not just a problem of having compatible libraries for dynamic linking, but also for fetching the correct version of every dependency before compilation. If these dependencies are not managed automatically, this can go wrong.

Once a proper dependency management is in place (e.g. all major Linux distros have package managers like apt or rpm, various language-specific solutions like tlmgr, cpan, pip, gem, npm, maven, … exist)1 the cost of having dependencies is negligible when deploying your library.

And you should reuse existing code wherever possible: It is generally infeasible to rewrite everything yourself, and we can look much farther “standing on the shoulders of giants” (Newton). Abstraction is a prerequisite for building non-trivial programs.

Incorporating dependencies directly into your library (i.e. rewriting these dependencies) can be a valid option in some cases:

This case of Not-Invented-Here is justified, e.g. for legal reasons.

The required levels of performance can only be reached by finely tuned code.

No infrastructure for deployment exists, so everything has to be bundled together.

1: tlmgr (TeX), cpan (Perl), pip (python), gem (Ruby), npm (node), maven (java)

Title: Is it really possible to have libraries not depend on other libraries?

Body:
I often see the advice that you should try to make each library independent. And yet in reality I can never seem to achieve this. Is this BS advice or is it actually possibly in any realistic way?

Example: I write a 2D Vector library, I then use that to make a 2D collision library. I then build a 2D physics library that uses both the 2D Vector Library and the 2D Collision library. Am I seriously expected to figure out a way to make the physics library not depend on the other 2 libraries? Likely I'll eventually want to be able to serialize/deserialize the physics and collision data which will mean I'll want to make them further depend on some serialization library.

Another example: I have a string library with lots of string functions (think endsWith(str, ending) and startsWith(str, start) or whatever. I then write a templating library that uses my string library.

I rarely seem to be able to write a new library that doesn't use other libraries.

I could write interfaces and then write adaptors for all of those to attempt to decouple one library from another but it's unlikely to be performant and often the models of the different libraries mean that even if I could decouple with an interface trying to use a different library than the one originally decoupled will end up being impossible or massively non-performant.

So, is that original advice BS or is there some way to actually apply the advice in the real world?


问:
Is secretive systems development really possible?

An agency wants to develop a highly secret computer system using public contractors. So they hire different companies to implement different components of the system. When all the components are put together the system is functional, but each component on it's own does not reveal the true nature of the system. Often the nature of the system is controversial, illegal or dangerous.

That scenario has been played out many times in movies and books, but is it really possible to build such a computer system in the real-world without at least one company knowing the nature of the system.

As an example, in the movie Batman: The Dark Knight. Batman uses contractors to build a spy network that allows him to use mobile phones as sonar devices. He claims in the movie that no one knows the nature of the system, because it was out sourced to many different parties.

Sounds good in science fiction, but in the real world can systems been engineered this way. While I know parts of a system can easily be outsourced. Could an agency build a large complex computer system using contractors without anyone knowing the nature of the system?

答:
Yes, it is possible. There would have to be an architect (or a team) for the whole thing that would understand all of the pieces and their interactions at a very detailed level.

The requirements for each piece would have to be so specific that it would almost be easier to write the application. All of the pieces would have to follow the same style of application development (SOLID, DRY, DI, service oriented architecture, etc.). All of the pieces would have to have agreed upon communication protocols.

Such a build would take a long time, probably years due to the separation of concerns and later, integration testing.

There is one such example that I can think of that the public is aware of: ARPAnet (now known as the Internet). At the time it was built, it allowed government contractors and universities to communicate easily with ARPA. (I seem to remember hearing that it was at one time a secret project, but that could just be a bad bit in my memory...)


答:
It's going to be slow, expensive and unreliable if it works at all. While in theory the computers could hide some of the problems, remember that computers are built, maintained and installed by people. So is software. If you don't let the people talk to each other, the system will not work very well.

The key problem is that no-one must be able to guess the nature of the system from knowing every detail of one part of it. That means the parts have to be fragmented to a high degree (even the parts that do the integration). So there will be a lot of communication problems, compounded by the need to carefully filter the communication to prevent anyone knowing too much. You can't have the "spy on webcam" people saying to the "store files" people "this is webcam video", even accidentally. That means every communication between developers has to be filtered by a human being. Which makes communication slow as well as uninformative.

Debugging will also be a nightmare since no developer can be allowed to see the system running, and each part will have to have its own debugging infrastructure. So you, developer of the "pipe an audio stream from the network to the user interface" component, will have to debug the "sometimes it stutters" bug without knowing what the user interface is or where the audio comes from (ie, what device is on each end). It's going to be very tempting for you to say "my log is clean, it must be someone else at fault". Everyone else will be saying the same thing.

Another problem is that the "inside" team gets very large, and the bigger it is the more management it needs, which makes it bigger. It may end up being bigger than the team that could have developed the whole system inhouse.

I've worked in a large-ish bank that had similar problems. No so much because they were a secret organisation, but just because they were big and some people had to deal with a lot of systems. So if a foreign currency transfer failed, some poor user was looking at a bank internal monitoring program that said "ERROR: transfer failed", when the international currency transfer program says "error: success" and the recipient bank is saying "we got your request, where's the money"... and so on. Their solution was to have a team of "insiders", like me, who were contractors hired to provide tier three helpdesk support, but from the inside. So we had admin rights to pretty much everything (just like Snowden and Manning did), and our job was to sort out things that the outside contractors couldn't fix.

I suspect inevitably a system like this will fail because there are huge incentives for everyone to "just make it work", and very few for "don't tell people the critical information they need to make it work". Spy novels fix that by using threats to kill and appeals to patriotism as incentives not to talk. But in the real world the people paying the bills (government) want results now, and "but there might be a leak later" is much less important than whatever silly event has everyone excited right now. Even when the event was Manning leaking stuff, the response was to give Snowden more access rather than less. Ooops.

Title: Is secretive systems development really possible?

Body:
An agency wants to develop a highly secret computer system using public contractors. So they hire different companies to implement different components of the system. When all the components are put together the system is functional, but each component on it's own does not reveal the true nature of the system. Often the nature of the system is controversial, illegal or dangerous.

That scenario has been played out many times in movies and books, but is it really possible to build such a computer system in the real-world without at least one company knowing the nature of the system.

As an example, in the movie Batman: The Dark Knight. Batman uses contractors to build a spy network that allows him to use mobile phones as sonar devices. He claims in the movie that no one knows the nature of the system, because it was out sourced to many different parties.

Sounds good in science fiction, but in the real world can systems been engineered this way. While I know parts of a system can easily be outsourced. Could an agency build a large complex computer system using contractors without anyone knowing the nature of the system?


问:
When is it suitable to use inheritance
I recently had a small "argument" about inheritance with a friend. I think people overuse it a lot. Intuition tells me that that the only good reason for class inheritance is polymorphism - when there is a case that you want to treat uniquely object of different but related classes.

Our argument was about having a BaseEntity class for Entity Framework that only has Id property. My friend says it's good because he can have generic repositories then. W don't agree with him.

Usually there's no such thing as a generic repository, you'll end up with "Refused bequest" smell.

What's the point of treating let's say a user and an invoice uniquely? These are 2 totally different things.

Unfortunately I couldn't make any good points in spite of "it makes no sense". :)

After a while I also realized that I drifted away from inheritance itself and now I tend to use interfaces instead. Actually in my recent web project (quite a big one) I can't recall any inheritance. Now I'm not sure when it is an appropriate technique anymore.

So guys, please help me here.

What do you think about what I wrote?

Can you find any arguments I can use against my friend?

When it really  is a good practice to use inheritance? (Please be specific and throw some examples)

Please don't try to explain to me what the inheritance is all about. I'm very familiar with that and I used it a lot. Like I mentioned above, over time I just drifted away from it, because I couldn't find the right usage for it. Simply interfaces seem to be a better approach to me in most cases.

答:
Like you, I tend to favor composition over inheritance.  However, let me give you an example where I find inheritance works really well...

Let's say you have a screen where you're editing a list of Users.  So you have an entity called User which is your persistence object.  Then I prefer to present a flattened model of this to my UI for editing, since there's usually extra logic and checks going on:

```<code>class User
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

interface IEditUser
{
    string Name { get; set; }
    DateTime DateOfBirth { get; set; }
    int Age { get; }
    void CommitChanges();
    void Delete();
}
</code>```

Now when there's editing going on, we need to load the list of Users with the initial values, let them be edited, and then you can choose whether to Save or Cancel those changes.  Since handling a newly created User is much different than handling an existing User (some fields are only edited in one of those situations, the code for persisting them are different, etc.).  That's why I like to do this:

```<code>abstract class EditUserBase : IEditUser
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int Age { get { return DateTime.Today.Year - this.DateOfBirth.Year; } }
    public abstract void CommitChanges();
    public abstract void Delete();
}
</code>```

Then my class for tracking new users added to the list (but not saved to the database):

```<code>class EditNewUser : EditUserBase
{
    public EditNewUser()
    {
        this.Name = string.Empty;
        this.DateOfBirth = DateTime.Today;
    }

    public override void CommitChanges()
    {
        var user = new User()
            {
                Name = this.Name,
                DateOfBirth = this.DateOfBirth,
            };
        // persist to database
    }

    public override void Delete() {} // nothing to do
}
</code>```

...and finally a class for tracking changes to existing entities:

```<code>class EditExistingUser : EditUserBase
{
    private readonly User existingUser;

    public EditExistingUser(User existingUser)
    {
        this.existingUser = existingUser;
        this.Name = existingUser.Name;
        this.DateOfBirth = existingUser.DateOfBirth;
    }

    public override void CommitChanges()
    {
        this.existingUser.Name = this.Name;
        this.existingUser.DateOfBirth = this.DateOfBirth;
        // possibly make database call here
    }

    public override void Delete()
    {
        // code to delete this.existingUser from database
    }
}
</code>```

I've found this works really well.  It separates my editing logic from my entities, and separates the logic of creating a new entity from editing an existing one.  It also creates a place to put logic that's common to both new and existing entities (such as the Age calculated property, and yes I know it's not implemented right :)

Title: When is it suitable to use inheritance

Body:
Like you, I tend to favor composition over inheritance.  However, let me give you an example where I find inheritance works really well...

Let's say you have a screen where you're editing a list of Users.  So you have an entity called User which is your persistence object.  Then I prefer to present a flattened model of this to my UI for editing, since there's usually extra logic and checks going on:

class User
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

interface IEditUser
{
    string Name { get; set; }
    DateTime DateOfBirth { get; set; }
    int Age { get; }
    void CommitChanges();
    void Delete();
}

Now when there's editing going on, we need to load the list of Users with the initial values, let them be edited, and then you can choose whether to Save or Cancel those changes.  Since handling a newly created User is much different than handling an existing User (some fields are only edited in one of those situations, the code for persisting them are different, etc.).  That's why I like to do this:

abstract class EditUserBase : IEditUser
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int Age { get { return DateTime.Today.Year - this.DateOfBirth.Year; } }
    public abstract void CommitChanges();
    public abstract void Delete();
}

Then my class for tracking new users added to the list (but not saved to the database):

class EditNewUser : EditUserBase
{
    public EditNewUser()
    {
        this.Name = string.Empty;
        this.DateOfBirth = DateTime.Today;
    }

    public override void CommitChanges()
    {
        var user = new User()
            {
                Name = this.Name,
                DateOfBirth = this.DateOfBirth,
            };
        // persist to database
    }

    public override void Delete() {} // nothing to do
}

...and finally a class for tracking changes to existing entities:

class EditExistingUser : EditUserBase
{
    private readonly User existingUser;

    public EditExistingUser(User existingUser)
    {
        this.existingUser = existingUser;
        this.Name = existingUser.Name;
        this.DateOfBirth = existingUser.DateOfBirth;
    }

    public override void CommitChanges()
    {
        this.existingUser.Name = this.Name;
        this.existingUser.DateOfBirth = this.DateOfBirth;
        // possibly make database call here
    }

    public override void Delete()
    {
        // code to delete this.existingUser from database
    }
}

I've found this works really well.  It separates my editing logic from my entities, and separates the logic of creating a new entity from editing an existing one.  It also creates a place to put logic that's common to both new and existing entities (such as the Age calculated property, and yes I know it's not implemented right :)


问:
Why separate unit tests into an assembly
I primarily develop in .Net, and have been playing around with F#. It's a nice concise language, but I'm just using it for throwaway code currently. I've taken to sitting my tests in the same file as the main code that I'm writing.

I am under the unexamined opinion that this is done so that we don't have testing code floating around in production, and that we have separate dependencies for testing which we don't want to go to production.

This has raised the question for me: why do we traditionally separate out test assemblies and not just use conditional compilation?

答:
Unit testing can involve a number of different libraries and dependancies than the application that is associated with it.

Thinking of an application I recently wrote as a proof of concept (Java) - a simple CRUD app with unit tests against an in memory database.

```<code>WebApp | Unit Test
-------+----------
       | JUnit
       | Mockito
Tomcat | Jetty
Mysql  | HSqldb
</code>```

So in the web app, I'm just linking against Tomcat and Mysql.  Within the Unit testing I've got JUnit, Mockito, Jetty, and HSqldb that are being used.  So its more than just conditional compilation to try to remove, its also the various testing frameworks that are used that you don't want linked in with the main application.  Mockito, Junit, Jetty and HSqldb have no place at all in the production application - why include them as part of the linking and deployment for it?

When working with Maven (again Java), the directory structure looks like:

```
my-app
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `resources
    |
    `-- test
        `-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `resources
```

The resources directories are where one has the dependency injection information so that when the test runs, the test resources are used (allowing one to have the connection to the in memory database instead of production).

This structure also prevents AppTest from getting compiled in with the main application.  Or any of the resources for testing to get compiled in.  The build process doesn't even see the test directory.  Thus, the code that is tested is identical to the code that is deployed.

That last bit is the key - the code that is tested being the same as the code being deployed.  I remember my days back in college with some C code that had #ifdef DEBUG scattered through it, and on occasion there was code in there that had a side effect.  I'd take the debug off, and it wouldn't work.  Debug on, its fine.  The same issue exists with conditional compilation.  It can exist with testing too (if you start tinkering in the guts of the module while testing it, but this becomes harder to do bad practice because its easier to do it the right way.

The other bit is even if this code isn't code that you can invoke easily - having testing code of any sort in deployed code means that a malicious user may be able to find that function to invoke, or entry point to call that now exposes something you shouldn't let users get at.

Body:
Unit testing can involve a number of different libraries and dependancies than the application that is associated with it.

Thinking of an application I recently wrote as a proof of concept (Java) - a simple CRUD app with unit tests against an in memory database.

WebApp | Unit Test
-------+----------
       | JUnit
       | Mockito
Tomcat | Jetty
Mysql  | HSqldb

So in the web app, I'm just linking against Tomcat and Mysql.  Within the Unit testing I've got JUnit, Mockito, Jetty, and HSqldb that are being used.  So its more than just conditional compilation to try to remove, its also the various testing frameworks that are used that you don't want linked in with the main application.  Mockito, Junit, Jetty and HSqldb have no place at all in the production application - why include them as part of the linking and deployment for it?

When working with Maven (again Java), the directory structure looks like:

my-app
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `resources
    |
    `-- test
        `-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `resources

The resources directories are where one has the dependency injection information so that when the test runs, the test resources are used (allowing one to have the connection to the in memory database instead of production).

This structure also prevents AppTest from getting compiled in with the main application.  Or any of the resources for testing to get compiled in.  The build process doesn't even see the test directory.  Thus, the code that is tested is identical to the code that is deployed.

That last bit is the key - the code that is tested being the same as the code being deployed.  I remember my days back in college with some C code that had #ifdef DEBUG scattered through it, and on occasion there was code in there that had a side effect.  I'd take the debug off, and it wouldn't work.  Debug on, its fine.  The same issue exists with conditional compilation.  It can exist with testing too (if you start tinkering in the guts of the module while testing it, but this becomes harder to do bad practice because its easier to do it the right way.

The other bit is even if this code isn't code that you can invoke easily - having testing code of any sort in deployed code means that a malicious user may be able to find that function to invoke, or entry point to call that now exposes something you shouldn't let users get at.


问:
If one is to learn a new programming language each year, what should the list be?
In chapter one of "The Pragmatic Programmer" the first learning goal is:

Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getter struck in a rut. [...]

To achieve this over a career, the list of languages is likely to get quite long (particularly if you do not want to "progress" into management). Clearly the education of a programmer (or whatever form) is going to get you started with a core of commercially useful languages (the usual list from job posting: C, C++, Ruby, Python, JavaScript, C#, Java, VB, ...). Additionally a formal or informal learning programme is likely to have covered functional approaches (via something like Haskell, LISP or an ML derived language)

But once a reasonable subset of that list is learned- what's next, and why?

答:
Besides the ones you listed,

Haskell, F#, Clojure, OCaml, Lua, Go, D, Erlang, Objective C.


答:
Coding standards need to be identified so everyone knows what they are and then they need to be enforced. There should be consequences to not following the rules.

Here are the things that should provide some incentive:

Code reviews will be tedious and longer than necessary.

Code will be rejected more often.

Schedules will not be met.

If this person either doesn't have to worry about this because no one enforces your rules or they don't care if they are unproductive (and no one does anything about that), there's not much you can do about it.

Title: Dealing with co-workers who do not have a consistent coding style?

Body:
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?


问:
Using interfaces as part of encapsulation
I'm creating interfaces for a number of our existing classes for mocking reasons.  Many of these classes also have package scope methods as an attempt to give some level of encapsulation by ensuring only the controller can modify some of their state.  I had thought I could use this change to try to get cleaner encapsulation as well.

My question is two fold.  First, is it considered viable to use interfaces for encapsulation?  I could make certain methods not in my interface that are available in the class.  or I could have my IBar method have a getFoo method that returns an IFoo, but my bar class overrides getFoo to return a Bar.  The problem is that anyone could easily cast my Ixxx to the actual class, so is it really considered a worthwhile encapsulation?

My second question has to do with my model.  I would want my model to have some getAllFoo sort of methods that return IFoo objects.  however, I want my controller to have a way to fetch the actuall Foo implementation (ie, know that my IFoo is of type Foo) so that it has access to methods not in the interface.  What is considered the cleanest way to ensure my controller has access to the full class but other classes only see the interface?  I asume just casting the interface to it's concrete class would be considered rather sloppy?

答:
Whenever casting is a problem for encapsulation depends whenever you have Enabling or Directing attitude. For person with directing attitude, the fact that you can upcast to bypass the encapsulation is definitely a problem, so they probably won't see using an interface as proper encapsulation. But for person with enabling attitude, this is not a problem, because for them it is enough that interface tells programmer what methods are safe to use and that any programmer will be well aware of problems and risks that upcasting can bring and will not use it lightly.

There is also case of using public interface with private or internal class. Then the problem of upcasting goes away, because compiler won't allow access to the private class so you could upcast.

And lets not forget about reflection. Even if programmer is limited by encapsulation, reflection can usually get around it. So there is always a way to break encapsulation if programmer thinks it will solve his problems.

As for your model question. Where is the problem of keeping collection of Foo internally in controller but returning collection of IFoo to the outside world?


问:
Developing a dynamic site with Node.js
I'm trying to get some pointers on what the best methodology to follow for a web application would be.

First, some background: I've built two different APIs using Node.js where Node serves the data to clients using a JSON interface. The clients have both been iOS applications, making heavy use of Socket.io and Express.

Now, I'm trying to get into the world of website development- I'd like to be able to create a single-page application that is run in the browser, again using Socket.io and Express. However, I'm hung up a bit on what exactly I should do.

Should I host my site out of Nginx/Apache and use Node as simply a "data" server, funneling data through JavaScript on the client to update the site HTML?

Should I host it all through Node, adding routes for files as I go?

Should I attempt to create some form of "send a command via Socket.io to the client JS to build the page dynamically" type of framework?

Should I do something else entirely?
Basically, I'm an iOS and API developer unused to web technologies overall, trying to figure out how best to use what I know about Node's data serving methodology and apply it to a client side web app.

I've been reading tons of information online and, while helpful, it seems that everything seems to assume that I know a lot about web development already and am just trying to adapt it to Node, whereas instead the opposite is true: I know about Node but not about web development. I've looked into the MEAN stack, for example, and while I love the concept it doesn't appear (at first blush) that Angular is any more suited to Node than, say, jQuery (I'm sure I'm wrong here- there must be some reason 'MEAN' is a thing).

Any input is greatly appreciated!

答:
Should I host my site out of Nginx/Apache and use Node as simply a
  "data" server, funneling data through JavaScript on the client to
  update the site HTML?

Many people recommend this exactly. This article is about yesod, but I think it applies:

As fast as Warp is, it is still optimized as an application server,
  not a static file server.

Using Nginx, you can set up virtual hosting
  to serve your static contents from a separate domain. (It’s possible
  to do this with Warp, but a bit more involved).

You can use Nginx as
  either a load balancer or a SSL proxy. (Though with warp-tls it’s
  entirely possible to run an https site on Warp alone.)

Then

Should I attempt to create some form of "send a command via Socket.io
  to the client JS to build the page dynamically" type of framework?

That is what many people do, using frameworks like angular/ember/knockout/... It is a natural way of developping a single page webapp.

The main drawback is managing js-less browsers, used by blind people & search engine bots. A native app would not be of any help here, so you have to decide if those use case are important, knowing that some solutions may exist (such as crawling your own webapp with a headless browser to build a static limited version served to js-lss browsers).

Should I do something else entirely? Basically, I'm an iOS and API
  developer unused to web technologies overall, trying to figure out how
  best to use what I know about Node's data serving methodology and
  apply it to a client side web app.

No one can answer this one. It depends if you want to learn something new vs deliver something fast. And also your target audience. Discovering any new technology is scary at first. The fact that a web-app backend can be anything you want means there are constantly new backend tech appearing all the time. You have chosen node.js; I would focus on this first, maybe ignoring nginx for the moment.

The knowledge about web client development is hard to acquire, but is very reusable. And once you know node.js, you can read more easily about other backend techs.

Title: Developing a dynamic site with Node.js


答:
Should I host my site out of Nginx/Apache and use Node as simply a "data" server, funneling data through JavaScript on the client to update the site HTML?

Something should be responsible for the port 80. It should be either Nginx/Apache or Node. If you're going to use Node you can use it as your webserver.

Should I host it all through Node, adding routes for files as I go?

I can't totally get this one. You can implement your dynamic routes using Express for example and it's very simple. Also you should generally consider requests as URI not Files.

Should I attempt to create some form of "send a command via Socket.io to the client JS to build the page dynamically" type of framework?

You can go for Socket.io if you wish, however you're not limited to. AJAX is the other option, however you won't need it if you have already Socket.io in place.

Should I do something else entirely? Basically, I'm an iOS and API developer unused to web technologies overall, trying to figure out how best to use what I know about Node's data serving methodology and apply it to a client side web app.

If you really need to have a single-page/real-time application, then Node is a good choice. If you need just a simple website an scripting language like Python or PHP could be a better choice.

Regarding Angular and jQuery, the first one is more of your luxury house in Beverly Hills but the second one is kinda piece of land -- well, anywhere on earth!, that you can build anything on that: A luxury house, a farm or a factory. If you read about them separately you will simply understand that Angular is more willing do to things for your -- in it's own way, in contrast with jQuery that is more willing to help you out doing things on your own and in your own way. Both of them have their own use cases, so don't simply dismiss any of them, they're totally different animals.

Title: Developing a dynamic site with Node.js

Body:
I'm trying to get some pointers on what the best methodology to follow for a web application would be.

First, some background: I've built two different APIs using Node.js where Node serves the data to clients using a JSON interface. The clients have both been iOS applications, making heavy use of Socket.io and Express.

Now, I'm trying to get into the world of website development- I'd like to be able to create a single-page application that is run in the browser, again using Socket.io and Express. However, I'm hung up a bit on what exactly I should do.

Should I host my site out of Nginx/Apache and use Node as simply a "data" server, funneling data through JavaScript on the client to update the site HTML?

Should I host it all through Node, adding routes for files as I go?

Should I attempt to create some form of "send a command via Socket.io to the client JS to build the page dynamically" type of framework?

Should I do something else entirely?
Basically, I'm an iOS and API developer unused to web technologies overall, trying to figure out how best to use what I know about Node's data serving methodology and apply it to a client side web app.

I've been reading tons of information online and, while helpful, it seems that everything seems to assume that I know a lot about web development already and am just trying to adapt it to Node, whereas instead the opposite is true: I know about Node but not about web development. I've looked into the MEAN stack, for example, and while I love the concept it doesn't appear (at first blush) that Angular is any more suited to Node than, say, jQuery (I'm sure I'm wrong here- there must be some reason 'MEAN' is a thing).

Any input is greatly appreciated!


答:
Such things are routinely done in the world of classified systems development.  The key word is "compartmentalization".  A very few people know how everything fits together, and then the various teams are given specifications for pieces of the total system, that never put it together.

Some of the pieces may be completely unclassified, but their intended application is highly classified, meaning that you won't be told what it is for, just that it needs to meet these specifications.


问:
How Do You Determine Your Hourly Rate?
In pricing a service or product it is general practice to not merely charge for the effort spent and the costs involved + margin but from the value delivered down. As an independent consultant, how do you set the price of your work?

What is the process of determining your hourly rate as an independent software developer? If you have one, what is your hourly rate and how did you arrive at that figure?

What factors would you take into account.  Is the process of setting a hourly rate only based on balancing demand with supply so that supply (you and your time) doesn't get overwhelmed?

When are the good times to raise your rates?

Are there projects in which you have had to charge higher than other projects? If so, please cite examples.

Do you change your hourly rate based on what kind of development you are doing? (for example, .net programming more, and lesser for php programming)

Do you set hourly rates based on what type of business the client is? If so how?

If you know of any relevant articles or material on the topic of charging for programming services, please post the same.

答: Ask around your area and see what others are charging or just guess. If you are getting more work than you can handle, you're not charging enough.</p>

Title: How Do You Determine Your Hourly Rate?


问:
How should the database schema be migrated?
I am using a bunch of freelance programmers to develop a web application. We are in the early stages of development, meaning that we are making many changes to our database schema. We have one test database and one production database, we also have a replica of the live database, which gets a clone of the live database every night (mostly used to make it easier to recreate bugs found in the live web application. Since I use many freelancers, which I do not know, I often do not trust their database skills and they do not have any understanding of the outmost importance of the data in our live database.

My question is what kind of process you would recommend after a freelancer determines the need to make a change in a database. They will currently commit change to our database schema together with their pull request (on GitHub), so I can review their proposed database changes. They are also free to apply the changes to our live database. My question is then how I should migrate the live data to the new schema. I thought about asking the developer of a patch to also create an alter table statement, which I would run on the live database, but I do not trust that they will be careful enough. I prefer such migration to be automatic (at least in most cases) in order to be able to deploy on a daily basis, but I do not know whether that is at all realistic. I also need to have a process that I trust so much that I do not need to make any tests on the live system if I have tested a pull request on our test system (working with our test database).

How can this be done?

答:
If you don't trust the developers, I don't see how you can let them make changes to the live database.

Have them change the snapshot database, review and test that, and then you apply the changes to the production database.

Also, it might be worth considering whether you could reduce the number of changes you have to make to the database schema with a little bit better planning, or even whether it is really necessary to deploy to the live site daily.


答:
There are Database Wizard applications that they could probably help you to automate the process; However the general process of upgrading database should be like this:

First you need an Upgrade script, where you can safely upgrade your database Schema and Data from version 2.8.13 to 2.8.14, for example.

The script should be totally SQL -- ideally, and should carefully Select the existing data in your database, Create a new table or Modify the existing ones, Modify the existing data in order to fit the new column types, etc. if necessary, and then Insert the data into the new table.

Then, obviously, creating a back-up/snapshot of the database is a must before applying any changes on the production server.

This should make the upgrades on the production server much easier, if you constantly upgrade the database and don't dismiss any of the upgrade scripts, otherwise upgrading a 2.8.13 to 2.9.3 might be a bit of extra work. The upgrade script could be manually written by your developers/DBA, or be an auto-generated script via a third-party tool. Either way you need to manually check it out to make sure it won't break anything and apply it on the Staging environment before the actual Production database.

Note: Your database version probably won't match your application version. So you don't need to have an upgrade script based on your application version. You only need it when the database schema has been modified.

Title: How should the database schema be migrated?

Body:
I am using a bunch of freelance programmers to develop a web application. We are in the early stages of development, meaning that we are making many changes to our database schema. We have one test database and one production database, we also have a replica of the live database, which gets a clone of the live database every night (mostly used to make it easier to recreate bugs found in the live web application. Since I use many freelancers, which I do not know, I often do not trust their database skills and they do not have any understanding of the outmost importance of the data in our live database.

My question is what kind of process you would recommend after a freelancer determines the need to make a change in a database. They will currently commit change to our database schema together with their pull request (on GitHub), so I can review their proposed database changes. They are also free to apply the changes to our live database. My question is then how I should migrate the live data to the new schema. I thought about asking the developer of a patch to also create an alter table statement, which I would run on the live database, but I do not trust that they will be careful enough. I prefer such migration to be automatic (at least in most cases) in order to be able to deploy on a daily basis, but I do not know whether that is at all realistic. I also need to have a process that I trust so much that I do not need to make any tests on the live system if I have tested a pull request on our test system (working with our test database).

How can this be done?


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答: Syntax is just the view on top of the language's underlying semantics because programming is all about using the underlying semantic bricks to build something. If you don't understand the fundamental concepts the language uses then it doesn't matter how good you are at memorizing syntax, your code will be a horrible mess. As someone once said, "Good programmers have an interpreter and a compiler in their head." Notice how there is no mention of syntax because that's not where the real work happens.</p>

Title: Programmers forgetting syntax


答:
It is normal to have a build server with a very well control version of the compiler etc on it that builds the software, runs the tests and if the tests pass creates the installer using the same dlls that were tested.

There is an additional risk of configuration errors if the software is built in a different way for testing then for shipping.

Title: Why separate unit tests into an assembly

Body:
I primarily develop in .Net, and have been playing around with F#. It's a nice concise language, but I'm just using it for throwaway code currently. I've taken to sitting my tests in the same file as the main code that I'm writing.

I am under the unexamined opinion that this is done so that we don't have testing code floating around in production, and that we have separate dependencies for testing which we don't want to go to production.

This has raised the question for me: why do we traditionally separate out test assemblies and not just use conditional compilation?


答:
Say the system was for collection, storing and viewing of spy photos.

The storage team don’t need to know what zoom lenses are used or how the images are processed.

The collection team don’t need to know how long the images are stored for or how they are processed.   (There may be more then one collection team that does not know about each other)

Each processing team does not need to know how long the images are stored for, or where images are taken.   Each processing team does not need to know about what the other processing systems can do.

However they will all have some idea what the system does but not know how well it does it, or all of the details.


问:
Multi-level paging tables
Referring to the image here:

From http://en.wikipedia.org/wiki/File:X86_Paging_4K.svg

Could somebody please explain something for me? I don't get exactly how this works. As I understand it the page "directory" contains an entity which essentially points to the beginning of the "page table". However, surely all of the entities in the page "directory" would contain the exact same value? Or, does this mean we have 1x page "directory" but N page "tables" (at the same level in the page multi-level hierarchy")?

If there are N page "tables" and one page "directory" I get why the PD would point to one of the N PTs. If there aren't then I am really confused.

答:
That diagram should be read as:

The Page Directory (PD) is an array of Page Directory Entries (PDEs), pointed to by Control Register 3 (CR3).

The leftmost 10 bits of the address are used as an index into the PD.  The PDE at that position points to one of many Page Tables (PTs), specifically the PT that maps pages for the desired address.

The next 10 bits are used as an index into the PT.  The Page Table Entry (PTE) at that position points to one of many 4KB pages in memory, specifically the page that contains the desired address.

The rightmost 12 bits are used as a byte-index into the page.

Thus the memory location is at CR3 -> [a & 0xffc00000] -> [a & 0x003ff000] -> [a & 0x00000fff]

Title: Multi-level paging tables


问:
How did the "abnormal" options in shell commands appear?
These options which obscure me are like

ps aux, route -ee, gcc -fPIC xxx, find . -name xxx and so on.

The examples above aren't comprehensive.

I.e., I don't think that the argument handle function like getopt or getopt_long could handle all the "strange" options.

In the other hand, these handle ways aren't intuitive.

Why do GNU programmers or Unix/BSD programmers code in these ways?

答:
At least some of those are older than GNU and BSD and getopt/getopt_long. Some of those may even be older than Unix, or may be ports of programs that originated outside of Unix.

For an interesting case study, you could try to read up on how tar and cpio became unified into pax.