问:
Have Superclass Contain List of Subclass?
For the GUI of a program, I want it to list several items, all of which are, from a programming side, just subclasses. They can add one of these items to a list. I don't want to hard-code which subclasses there are. What would be the best way to allow the GUI to know about the subclasses, only having the base class to refer to?</p>

答:
First off: I think in this case, rather than populating the list with a class/subclasses of it, using some sort of interface may be the more appropriate design.

The best approach is probably going to depend on your language. If it supports reflection (like C# or Java), you may be able to look for other classes that subclass/implement your interface.

If it doesn't - or if you want a simpler solution - you can simply keep the list of available types in some sort of configuration file/table that gets read in at runtime.


答:
@Andrew Timson (+1) makes a superb point about the use of reflection (if possible) and using an interface.

From an Object Oriented Design point of view, Interface's are going to be a much nicer way to go - unless of course there is enough logic in common/inherited to warrant subclassing. This could be argued as part of the "Dependency Inversion Principle" at work; "Depend upon Abstractions. Do not depend upon concretions.". You're already leaning towards quite a clean solution that adheres to this by avoiding the hard coding though, so nice one!

In addition to that, Reflection could be the way to go. There's some more information on when reflection should be used over here, on StackOverflow

Other than that, you could use something like an adapted Observer Pattern and have each new instance of a given sub-class "register" itself upon initialisation. So there is an object you can query to get all of the objects in question; you could make this a Singleton to ensure it's always accessible throughout the lifecycle of the application - and to make sure there is only ever one object to query.

That's not the neatest solution, but it is another one that could work.

ContentLicense: CC BY-SA 3.0

Title: Have Superclass Contain List of Subclass?

Body: For the GUI of a program, I want it to list several items, all of which are, from a programming side, just subclasses. They can add one of these items to a list. I don't want to hard-code which subclasses there are. What would be the best way to allow the GUI to know about the subclasses, only having the base class to refer to?</p>


问:
Storing application users in SQL: create a new "Users" table or use built-in database user management?
I am specifically interested in SQL Server, but the same question applies in general.  When creating a new application, the way I see it, there are two options:

Create a table called "Users" and store the user name, password, etc.  Set up one database user called "application" (and possibly more users for various components of the system).

Set up each application user as the database user.  This may allow for easier single log on setup on Windows-based systems.

Which approach is generally preferred?  Why?  What are the drawbacks and benefits?

答:
Another advantage of using the ad account or similar is that in your database itself you can run in built in functions to work out who is logged in. This can be useful for things like auditing, or to know who is accessing your database at any point in time using the tools provided by your database.

However as previously mentioned this doesn't scale particularly well. Lots of open connections on your database via different users is expensive in terms of server resource.

Using either scenario, for most larger apps, you're going to have a users table either way. Whichever authentication method you use, once you know who that user is you will likely need to know more about them - what their date if birth is, their nationality, financial authorisation limits, permission to click on the save button... Very often you will use a users table and associated tables to store whatever you need to know for the app.

Some frameworks, such as asp.net for example, provide tools that will automatically give you templates for maintaining your own user tables.


答:
In SQL Server, you create logins at the instance level and users at the database level.  This can be confusing, but consider that the instance login is for actually gaining access to instance objects, whereas the users are for assigning roles and rights in the database.  If, for example, you restore a database from one machine with one set of logins to another instance on another machine, your logins will only be those configured on the target, whereas the users will still be included in the restored database - they just can't log in.

If you are using Windows integrated security then this is all you need to do.  You can save the user name to a column as shown:

'insert into [Companies] (DateAdded, AddedBy)

'    values (convert(varchar(50), getdate()),

'    USER_NAME(DATABASE_PRINCIPAL_ID()))

If you have thousands of web subscribers, then you need to define your own security layer.  If you're using ASP.NET, you can create a web based project where the Visual Studio program will script all this for you to start with.

Title: Storing application users in SQL: create a new "Users" table or use built-in database user management?

Body:
I am specifically interested in SQL Server, but the same question applies in general.  When creating a new application, the way I see it, there are two options:

Create a table called "Users" and store the user name, password, etc.  Set up one database user called "application" (and possibly more users for various components of the system).

Set up each application user as the database user.  This may allow for easier single log on setup on Windows-based systems.

Which approach is generally preferred?  Why?  What are the drawbacks and benefits?


问:
Client-side javascript: How to include third party frameworks?
When developing web apps you often build your app on top of some frameworks like Twitter's bootstrap. These frameworks come with less/sass/stylus, javascript, images and sometimes webfonts.

I'm wondering how to embed these frameworks in my app. Most of my apps are build using some grunt tasks that compile my coffeescript and stylus to javascript respectively css.
Because I'm not shipping third party code (e.g. frameworks) with my app I add them as a dependency. This allows me to install e.g. frameworks using a package manager like npm or volo.

Handling small javascript libraries (which consist only of one file, no assets) is easy. I install them in a vendor dir and update my require.js conf. But if the library has images or less/sass/stylus/css files attached I'm always struggling how to handle them:

Paths to assets in the css files or javascript files of these libraries are often hardcoded (relative)

less/sass/stylus has to be compiled (which I can do with a grunt task)

Copy all third party assets into my folder structure?

Should I include third party assets (stylesheets, javascript) in my own files and minimize them together?

If I use stylus and the framework uses sass I have to install a lot of further dependencies

I think I'm not the only one who has these problems so I'm looking for solutions, best practices or some general tips.

答:
If you are doing this stuff for a public facing website, I would go down the path of using someone's CDN if possible. It'll probably make your site faster (if the CDN is up to scratch) and use less bandwidth for your own server. They will have set the content expiration up properly and it should be cached properly.

However if it's an internal app, you might not want to rely a third party CDN - so that your app keeps working even if your internet connection drops out. Or if you have a dodgy internet connection your app will be more reliable. In this case I would download everything, minify and bundle it together (well as much as is reasonable).

To answer your other concerns:

Paths to assets in the css files or javascript files of these libraries are often hardcoded (relative)

Yep, it's a pain, you're gonna have to deal with it somehow. I use ASP.NET's bundling and minification (System.Web.Optimization) which lets you set the base URL so that relative paths from within your CSS and Javascript work.

less/sass/stylus has to be compiled (which I can do with a grunt task)

I haven't used any of them, but sounds like you've got it covered.

If I use stylus and the framework uses sass I have to install a lot of further dependencies

Yep, that's one of the tradeoffs for using a framework, especially one with dependencies. It's your call if you think the benefit of using it outweighs the pain of managing it.


问:
Using absolute paths for build dependencies
Currently we are using Source Safe and have started migration to Subversion.
All of our external SDK's(> 500 MB) are held in Source Safe right now, and I am looking for ways to move them from VSS to a repository.

We have C++ (mostly), C# (many), Java (few) projects. Hundreds of projects, all running on Windows.

I looked at a couple of dependency managers but I'm not satisfied:

NuGet - good for .Net but painful for C++

Ivy - not look in depth, but doesn't seem acceptable for C++

First question: what else should I check? It should be easy to use for a front-end developer. Best case is a simple build within the IDE.

Currently I am inclined to this solution:

Allocate some rarely used drive, like S: and declare it as 'DEV HOME'.

Then place externals here:

```<code>S:\SDK\boost\1.30\...
S:\SDK\boost\1.45\...
S:\SDK\oracle\agile_9.0.0.0\...
S:\SDK\IBM\lotus_8.0\...
S:\SDK\IBM\lotus_9.0\...
S:\Tools\NuGet\nuget.exe
S:\Tools\clr\gacutil.exe
</code>```

Autobuild machine will hold mastercopy of this 'DEV HOME'. Every developer should copy necessary SDKs from autobuild machine to local and create a 'fake' disk with subst.

I can't find any big problems with this solution:

Branches. Projects in different branches contain references to different versions of SDK (boost for example)

Version of external component will not change too frequently, so there will not be  hundreds of, say, boost versions.

Easy for developers to setup.

Absolute paths supported by any tool.

Minor problems:

Personally for me it is not beautiful solution.

Disk (S:) can be busy

Can't be done in Linux (but currently we're not interested in it)

Second question: what problems can you see with this solution?

答:
To answer your second question - the main issue with using a shared drive for hosting code is that the performance won't be optimal. You will probably come across concurrency problems and speed in general.  I would recommend that you either have each's project's dependencies stored with the SVN repo, but outside of the main trunk folder (to avoid duplication on branching). Or if you have lots of common dependencies, you could have a separate repository for that and use SVN's "externals" to manage it.

In terms of dependency manager no-one can recommend one to you that will cater for all of your individual needs, each one has benefits and trade offs, especially considering your large range of languages. Back to google I'm afraid :)


答:
you can do this: </p>

```<code>import java.util.*;
class Super {
    Super() {
        subclasses.add(getClass());
    }
    static List<Object> subclasses=new LinkedList<Object>();
}
class Sub1 extends Super {
}
class Sub2 extends Super {
}
public class P205597 {
    public static void main(String[] args) {
        new Sub1();
        new Sub2();
        System.out.println(Super.subclasses);
    }
}
</code>```

Body:
you can do this:

import java.util.*;
class Super {
    Super() {
        subclasses.add(getClass());
    }
    static List<Object> subclasses=new LinkedList<Object>();
}
class Sub1 extends Super {
}
class Sub2 extends Super {
}
public class P205597 {
    public static void main(String[] args) {
        new Sub1();
        new Sub2();
        System.out.println(Super.subclasses);
    }
}


问:
When is a catch clause empty
I saw lots of questions and explanations regarding empty catch clauses but I was never actually sure what "empty" means.

Is a catch clause like this empty? It clearly isn't empty for the eye because there is one line of code. But the catch is not really handled. Instead the error is just logged.

```<code>try {
    // do some work
} catch (SomeException e) {
    logger.error("Some error", e);
}
</code>```

I see this fairly often because there are a lot exceptions where you just can't do something about it if it fails. The consequence is that the error is not fully swallowed but at least logged.

So the question is: Is this bad code if you "just" log the error and don't do anything about?

答:
This is an empty catch:

```<code> catch (SomeException e) {
 }
</code>```

It is a very bad idea, because you're silently ignoring the exception. And even if that is the actual intention, then you should have at least a comment in there to tell future-you (or any other developer) why it should be empty.

Arguably, this one is still empty:

```<code> catch (SomeException e) {
   // nothing to do because we frobnicated the foo before
 }
</code>```

But at least this time we know that some thought went into it and the author thought that a do-nothing catch block is correct here.

Anything that adds logging or other exception handling is not "empty" in any meaningful way.

Whether or not some handling/logging code is sufficient at any given place, is an entirely different question: sometimes simply logging the exception is the right thing, at other times more drastic steps must be taken.

Title: When is a catch clause empty

Body:
This is an empty catch:

 catch (SomeException e) {
 }

It is a very bad idea, because you're silently ignoring the exception. And even if that is the actual intention, then you should have at least a comment in there to tell future-you (or any other developer) why it should be empty.

Arguably, this one is still empty:

 catch (SomeException e) {
   // nothing to do because we frobnicated the foo before
 }

But at least this time we know that some thought went into it and the author thought that a do-nothing catch block is correct here.

Anything that adds logging or other exception handling is not "empty" in any meaningful way.

Whether or not some handling/logging code is sufficient at any given place, is an entirely different question: sometimes simply logging the exception is the right thing, at other times more drastic steps must be taken.


问:
Are wikis really appropriate to store documents for software development?
Everybody knows that well-documented software development leads to success. However, it usually means that not only plain text but also binary content will be involved in the document, such as a UML diagram. And I've heard many people say that. The version control system is not the appropriate place for the binary files. I totally understand and agree with the issue. I asked several seasoned developers where the best place to store documents should be and the answer I got was "wiki". Wiki is good but I considered another potential issue. How can the source code which has been stored in a version control system connect to its related document in wiki? Let's say someone clones the repository of git or mercurial. How can he/she find the document easily? Or have I just missed something?

I know some wiki systems have the ability to integrate with source control systems. But my concern is not about the ability of integration. If you have cloned source code from a git repository and after a while you get on a train and want to continue to work offline on the train (which is a big feature of DVCS). Then you suddenly realize you don't have any access to document since you are working offline on the train. On the other hand, if the document was stored in git repository you would have access to the document with repository cloned.

答:
It makes sense to store the documentation in the same repository as the source code. Sphinx seems like a good option to me.

it takes reStructuredText files as input, which is easy to edit and diff

it generates hyperlinked output (HTML, PDF, ...)

you can reference your source code (Python, C, C++, JavaScript)


答:
I think one would have to argue that it will not often be good code - its rather better than swallowing the error completely (or at least its better than doing so without clear explanation).

The basic problem is that in the same way that the code never throws, in my experience no-one will look at the logs unless there is an issue (or until the issue that its been hiding is uncovered by other means). I speak from practical experience as I have code that's not dissimilar to the above.

That said if you're catching and swallowing specific exception (as the code implies) and you explain why you're doing so then it may be perfectly reasonable.

What is not reasonable is a generic catch-all that does that - because then the you're getting into unforeseen consequences i.e. whilst it will swallow the trivial not critical error its there to deal with it will also swallow the show-stopper that's gently corrupting your data...

Title: When is a catch clause empty

Body:
I saw lots of questions and explanations regarding empty catch clauses but I was never actually sure what "empty" means.

Is a catch clause like this empty? It clearly isn't empty for the eye because there is one line of code. But the catch is not really handled. Instead the error is just logged.

```<code>try {
    // do some work
} catch (SomeException e) {
    logger.error("Some error", e);
}
</code>```

I see this fairly often because there are a lot exceptions where you just can't do something about it if it fails. The consequence is that the error is not fully swallowed but at least logged.

So the question is: Is this bad code if you "just" log the error and don't do anything about?


答:
I guess it depends whether the exception is checked or is a runtime exception.

The idea behind checked exceptions (the ones you are required to "catch") is that they are errors which the application can recover from. So when caught, you should ideally provide a logic to recover from these exceptions. While you may rethrow them up the call heirarchy, it is best to handle them as quickly as possible (never let your clients do what you can do for your clients).

Runtime exceptions on the other hand, are normally not recoverable. They leave the application in a bad state. More often than not, the only way to handle these exceptions is to log as much information to aid your investigation. Typical applications would have "catch-all" block to handle all runtime exceptions.

Title: When is a catch clause empty


问:
Is it common to separate back-end and front-end into two positions on web development projects?
At a web startup, is it more common to have an engineer working the front-end AND back-end of the feature (basically in charge of the whole feature)? Or have engineers separated between the back-end and front-end?

Which ones are more beneficial and for what situations?

The downside, I've noticed, regarding having one engineer in charge of the whole feature is that the person might only be particularly strong in either frontend or backend development but not both, thus sometimes having a decrease in speed and quality.

Having frontend and backend developers on one feature increase the speed of the feature and the quality AND it encourages collaboration. But I am concerned about having 2 engineers working on one feature which may be a poor use of resources since the 1 engineer can be placed on another feature to work on.

What is the common/best practice for allocation backend/frontend engineering resources at a small early-stage startup? And then how will it change as it grows?

答:
I think the question is wrong.

All startups I took part in did not have a FE-BE only architecture.

Most startups I know have:

Core - the actual product that exposes an interface

UI - BE and FE. The BE uses the Core's API.

APIs are stateless and easily mocked - even without the need of a Core Developer.
Hell, if I had to start a project from scratch I might start with an entire UI that works purely on mocks - which will be great for presentations.
Most of the feedback is due to UI. Customers note that more - ( depends on your target audience. )

For example - Google Search has the Core component which crawls the web, indexes it etc.. and the Google UI is a totally different world.
This core can easily support non WWW searches, while the UI cannot.

This way your UI is "pluggable" and you have separation of concerns.

You referred to Development knowledge, however you're overlooking project management aspects. While the core team might need 2 weeks sprint duration, the UI team will use CI - everything is uploaded all the time. The Core team will need backward compatibility while UI will not.

Language differs. You will probably want C developers for the Core component - and you will be ok if it runs on a single OS, where as the UI will be written in a Cross OS Language.

Tests differ. The UI test world is one of the most complex I know in software development. Most startups neglect it and regret this decision later on.
You cannot separate BE and FE when testing. It has to be a single unit that handles it.

Open Source UI - one of the greatest benefits of separating the two is that you can open source your UI. UI project need open source support.

I cannot imagine a UI developer that cannot understand the entire session feature. You know - where you login and stay logged in between different requests. True they might know PHP and not Java.. but the BE concept should be clear (e.g. use an encrypted cookie). The specific language barrier is wrong - every developer should be willing to work in any language. Who would've thought they would write BE in JavaScript a couple of years ago?

If you go on having 3 teams : Core, BE and FE, it is a waste of resources imho. What about DB? should you have DBAs? Why should a BE developer know DB and a FE developer not know BE and DB? There's no limit.

If you require experts, and you will, outsourcing them works pretty well. They usually deliver quality code and they do it quite fast. You do not necessarily want them in-house because you will get lost if they leave. Besides you can get great advice online today. Cutting edge stuff might require different approach.

So the outcome is basically a very thin BE in the UI that every FE developer can develop. If you have a thick BE in the UI you most probably have some API functionality required in the Core.

There's always at least one developer that stands out of the rest.
Given such a thin FE, he/she  can manage giving support (not develop) other developers in BE code. My opinion is that this developer is in a very good position and should be awarded appropriately (not in salary though, something else). I also trust that they will be able to handle build process and build properly.

This model gives you a great flexibility regarding BE development. The BE world have known several turnarounds in the last couple of years, so I don't recommend relying on BE stability too much anyway. Core is a different story.

There still remains the question - should FE and BE be the same project? You should note the following

Static resources are best served from front-server. Since Front-End servers (e.g. nginx) are very powerful and since you can use Cache for static resources, you can manage with a single deployment of your static resources (which should be all HTML content, JS, CSS, Images).

Backend code does not have the same luxuries, so you must have a distributed system - which is also managed by a front-server.

FE code is highly to be reused with all the new technologies that support JavaScript. You can now write Desktop and Mobile applications with JavaScript.

The build process is completely different - and that can even include patches delivery, upgrade, installation etc..

I can go on, but I hope it is clear that I think BE and FE should be the same team, but maybe different projects.


问:
Python Multiprocessing with Queue vs ZeroMQ IPC
I am busy writing a Python application using ZeroMQ and implementing a variation of the Majordomo pattern as described in the ZGuide.

I have a broker as an intermediary between a set of workers and clients. I want to do some extensive logging for every request that comes in, but I do not want the broker to waste time doing that. The broker should pass that logging request to something else.

I have thought of two ways :-

Create workers that are only for logging and use the ZeroMQ IPC transport

Use Multiprocessing with a Queue

I am not sure which one is better or faster for that matter. The first option does allow me to use the current worker base classes that I already use for normal workers, but the second option seems quicker to implement.

I would like some advice or comments on the above or possibly a different solution.

答:
You might want to consider a third possibility for implementing remote logging. If you use the standard Python logging module you can consider using the logging.QueueHandler class in your workers, clients and broker, and the logging.QueueListener class in your remote logging process.

Instead of using the normal Python multiprocessing.Queue as the transport between your application processes and your logging process, implement your own Queue replacement class using ZeroMQ with duck typing to have your class be a drop-in replacement for the standard Python Queue. In this way your application will be able to run unaltered in any environment from a single multi-core computer through distributed data centres.

To summarize, use a standard Python logger with a QueueHandler in all your workers, clients and brokers and create an independent process based on QueueListener and the Python logging handler(s) of your choice to handle the heavy lifting of logging.


问:
In Java, why were protected members made accessible to classes of the same package?
From the official documentation...

```
Modifier    Class   Package Subclass    World
public      Y       Y       Y           Y
protected   Y       Y       Y           N
no modifier Y       Y       N           N
private     Y       N       N           N
```

The thing is, I can't remember having a use case where I needed to access protected members from a class within the same package.

What were the reasons behind this implementation?

Edit: To clarify, I'm looking for a specific use case where both a subclass and a class within the same package needs to access a protected field or method.

```<code>package some.package;
public class A {
 protected void protectedMethod(){
  // do something
 }
}

package another.package;
public class B extends A{
 public void someMethod(){
  // accessible because B is a subclass of A
  protectedMethod();
 }
}

package some.package;
public class C {
 public void anotherMethod(){
  // accessible because C is in the same package as A
  protectedMehtod();
 }
}
</code>```

答:
symmetry?

It's rare to need such access, which is why default access is so rarely used. But sometimes frameworks want it for generated code, where wrapper classes are placed in the same package that interact with your classes directly, going to members instead of accessors for performance reasons.. Think GWT.


答: A good example that immediately comes to mind is utility classes that are used a lot in the package but you don't want public access (behind-the-scenes-image-loading-from-disk, handle-creation/destruction classes, etc.) instead of making everything [Java's equivalent friend access modifier or idiom in C++] of every other class everything is automatically available.

Title: In Java, why were protected members made accessible to classes of the same package?

Body:
From the official documentation...

```
Modifier    Class   Package Subclass    World
public      Y       Y       Y           Y
protected   Y       Y       Y           N
no modifier Y       Y       N           N
private     Y       N       N           N
```

The thing is, I can't remember having a use case where I needed to access protected members from a class within the same package.

What were the reasons behind this implementation?

Edit: To clarify, I'm looking for a specific use case where both a subclass and a class within the same package needs to access a protected field or method.

```<code>package some.package;
public class A {
 protected void protectedMethod(){
  // do something
 }
}

package another.package;
public class B extends A{
 public void someMethod(){
  // accessible because B is a subclass of A
  protectedMethod();
 }
}

package some.package;
public class C {
 public void anotherMethod(){
  // accessible because C is in the same package as A
  protectedMehtod();
 }
}
</code>```


答:
The use cases for the protected/package access modifier are similar to the ones for friend access modifiers in C++.

One use case is when implementing the Memento pattern.

The memento object needs to access the internal state of an object, to hold it, in order to serve as a checkpoint for undo operations.

Declaring the class in the same package is one of the possible ways to achieve the Memento pattern, since Java has no "friend" access modifier.


问:
Is this Java Compiler error message incorrect? (byte loss of precision)
The following IMHO valid java program doesn't compile because the Oracle 1.7 javac compiler thinks there's a possible loss of precision in lines 5 and 6. If you uncomment line 3 and comment out line 4, it compiles fine.

Would someone explain why the compiler believes there is a loss of precision on the assignment to either byte b2 or b3?

```<code>public class BUG {
    public static void main( String[] args ) {
        //final byte b1 = 9;
        byte b1 = 9;
        final byte b2 = -b1;    // fine if line 3 is uncommented and line 4 is commented
        final byte b3 = 0 - b1; // fine if line 3 is uncommented and line 4 is commented
    }
}
</code>```

If my sample code is correct, then I'd like to report this as a bug but I can't find out where. Would someone explain what the compiler error message is saying in this case and why it's correct?

答:
It's not a bug, it's acting exactly as specified.

With the final byte b1 the compiler is sure that b1 will have the value 9 and -b1 becomes a compile time constant expression. The compiler can then check that the value is still acceptable for a byte and let's you do it.

When b1 is not final then -b1 is an expression like any other and as such b1 will be promoted to int (see JLS §5.6.1. Unary Numeric Promotion). And since the conversion from int back to byte can result in loss of precision, the compiler doesn't allow it (without an explicit cast).


答:
I'd say this has two parts:

The default, "package", access is useful in wide range of cases, because classes are not always good unit of encapsulation. Various composite objects where some object acts as collection of other objects, but the items must not be publicly modifiable, because there are some invariants across the whole collection, so the collection needs to have elevated access to the items. C++ has friends, Java has package access.

Now the "package" access scope is basically independent of the "subclass" (protected) scope. So you'd need additional access specifiers for package only, subclasses only and package and subclasses. The "package" scope is more restricted as set of classes in a package is usually definite while a subclass may appear anywhere. So to keep things simple, Java simply includes the package access in the protected access and does not have extra specifier for subclasses-but-not-package. Though you should almost always think of protected as exactly that.


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
You could put all the private/protected keys as system environment variables. Your configuration file will look like this:

```<code>private.key=#{systemEnvironment['PRIVATE_KEY']}
</code>```

This is how we handle those cases and nothing goes into code. It works very well combined with different property files and profiles. We use different property files for different environments. In our local development environment we put the development keys in the property files to simplify the local setup:

```<code>private.key=A_DEVELOPMENT_LONG_KEY
</code>```

Body:
You could put all the private/protected keys as system environment variables. Your configuration file will look like this:

private.key=#{systemEnvironment['PRIVATE_KEY']}

This is how we handle those cases and nothing goes into code. It works very well combined with different property files and profiles. We use different property files for different environments. In our local development environment we put the development keys in the property files to simplify the local setup:

private.key=A_DEVELOPMENT_LONG_KEY


问:
When being a technical genius is not enough to be a successful developer?
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.

答:
Team work / communication :

to be able to explain your solutions or your problems

to be able to work with other people without making them feel bad (in any way) - to make them feel working with you is pleasant

Without those skills, you can't work in team, and if you can't, you'll not be able to get in a company that require that (and almost all of them require teamwork, naturally). You could still be freelance and work on projects that don't have other people to work on, but you still have to communicate with people from other companies.

Even for learning, if you can't communicate with a lot of different people, like on the web, then you might not be able to do better in real life and in society (whatever the job) it's an handicap.

edit> In interview, team-work/socialization/communication is really easy to check, it might be the easiest thing. You just have to ask some questions, not technical, questions easy to answer or simply questions about what the candidate think about something or what the candidate like or dislike in a domain or another. Make him talk. You'll see.

ContentLicense: CC BY-SA 2.5


问:
Can we illustrate a CPU pipeline with a UML sequence diagram?
I study multicore pipelining and the diagrams are not UML sequence diagrams for instance

Why not remake this diagram like an UML sequence diagram, would not that be more clear so that we can see both how time progresses as well as the data paths since I do not think it is clear distinction between data path and time?

In UML time goes downward and the data path goes right and left.

Can you comment or answer why pipelining generally is not illustrated with UML?

答:
I haven't seen a pipeline illustrated with a UML sequence diagram yet. I am not saying it is not possible (I think it is) but it would be a lot more complicated and abstract than your FBD which shows the actual architecture of the simplified processor.

The main problem I see with the sequence diagram is that all the stages happen in parallel and it could become really messy if you would try to illustrate things like forwarding or stalling in it.

Also with the FBD you can demonstrate how to build the processor. You can incrementally add instructions and see how the design evolves. You end up with quite a mess but if you followed from the beginning then it should be much easier to understand it.


问:
which is better of these two architectures and why
PhpServer will handle gSoap requests and http requests from clients.

PushServer will push notifications to clients and act a file server.

There are many server machines. Every PhpServer will communicate with a specific PushServer when needed. Every PhpServer needs to register itself to a PushServer letting the PushServer to help push notifications to clients.

Here are two architectures:

1) Architecure A

This architure will run each PushServer with a PhpServer on the same machine. Each client will register itself to a PhpServer and the PushServer which is running on the same machine with the PhpServer

```<code>                      |Database|
                      _____|_____
                     |           |
                     |           |
              (|PhpServer| + |PushServer|)   //a same server machine
                     \            /
                        |Client|
</code>```

2) Architecture B

This architure will run each PushServer on a single machine. Each client will register itself to a PhpServer and the PushServer which the PhpServer registers.

```<code>                      |Database|
                      _____|_____
                     |           |
              (|PhpServer|)  （|PushServer|） //two server machines
                     \            /
                        |Client|
</code>```

Which architecture is better and why?

[update]

We are worried about performance, extensibility, and flexbility. Actually the first achitecture is what we currently have and if we choose the second one, we need to modify our software: PhpServer, PushServer and Client. Thus, unless the second network architecture is much better (from load-balancing or network application design perspective), we won't choose the second one.

答:
The basic question "one or two servers" is the wrong question asked, IMHO. As I understand your question it should be more asking if the "Pull" and the "Push" functionality should be handled by the same server application.

My plug would be to separate these functionalities as best as possible, makes the whole stuff easier to develop and maintain.

That said, it simply a question of server load and network architecture if you have the two instances running on the same machine or on two separate ones.


问:
Java Compiler and VM Compatibility
A co-worker and I recently had a discussion about Java versions and the JVM. I use Java 7 but we use Java 6 for our client (while he says that some are still on 5). My immediate thought was, why can't we target those VMs too?

The Java VM is somewhat different than a real machine in that it has a bunch of runtime features. Type checking, exception handling, garbage collection, etc. But it's still a virtual machine which has a bytecode. (Which is why we can have things like C to JVM compilers.) So why can't we target older VMs with newer version of Java? Why does the language and the runtime have to be tied together? Besides the obvious performance penalties, it seems like it should be completely possible to compile Java 7 code to the Java 6 JVM. (And considering how little changed from Java 6 to 7, I can't imagine the compiler changes being that extensive.)

答:
the main culprit are the library updates, java is crazy backwards compatible such that code written for 1.1 will still run on java 8 without needing to be recompiled

the biggest changes are internals and JRE libraries, at bytecode level not much as changed

it is up to you(r manager) to decide whether you'll target 1.5 or 1.7 and then deal with the limited library available

Title: Java Compiler and VM Compatibility


答:
If the JVM team was to start all over again they would probably look to have a modularised JVM so that you could mix and match JVM implementations and language features.  For example you could have Lambdas implemented as anonymous inner classes or using invokedynamic and MethodHandles.

Hmm, actually they are looking at something like doing this for Java 9 with project Jigsaw

Title: Java Compiler and VM Compatibility

Body:
A co-worker and I recently had a discussion about Java versions and the JVM. I use Java 7 but we use Java 6 for our client (while he says that some are still on 5). My immediate thought was, why can't we target those VMs too?

The Java VM is somewhat different than a real machine in that it has a bunch of runtime features. Type checking, exception handling, garbage collection, etc. But it's still a virtual machine which has a bytecode. (Which is why we can have things like C to JVM compilers.) So why can't we target older VMs with newer version of Java? Why does the language and the runtime have to be tied together? Besides the obvious performance penalties, it seems like it should be completely possible to compile Java 7 code to the Java 6 JVM. (And considering how little changed from Java 6 to 7, I can't imagine the compiler changes being that extensive.)


答:
Using a wiki to store documentation make a lot of sense to me.

Veracity is an example of a DVCS that allow tighter integration of wiki content and source code.

Title: Are wikis really appropriate to store documents for software development?

Body:
Everybody knows that well-documented software development leads to success. However, it usually means that not only plain text but also binary content will be involved in the document, such as a UML diagram. And I've heard many people say that. The version control system is not the appropriate place for the binary files. I totally understand and agree with the issue. I asked several seasoned developers where the best place to store documents should be and the answer I got was "wiki". Wiki is good but I considered another potential issue. How can the source code which has been stored in a version control system connect to its related document in wiki? Let's say someone clones the repository of git or mercurial. How can he/she find the document easily? Or have I just missed something?

I know some wiki systems have the ability to integrate with source control systems. But my concern is not about the ability of integration. If you have cloned source code from a git repository and after a while you get on a train and want to continue to work offline on the train (which is a big feature of DVCS). Then you suddenly realize you don't have any access to document since you are working offline on the train. On the other hand, if the document was stored in git repository you would have access to the document with repository cloned.


答:
I think the main reason is simply that the demand for this feature is not very high, because upgrading to newer JVMs is generally quite painless. And the kind of organizations and people who insist on running outdated JVMs anyway are probably not keen on using the newest language features either.

Of course, it's certainly possible - nobody prevents you from writing such a compiler. But the only example I'm aware of that saw widespread use is Retroweaver, which let you use the Java 5 features on 1.4 JVMs. But then, Java 5 has the biggest, most useful new features of any Java version, so there was much more value in having this than with other versions.

Title: Java Compiler and VM Compatibility


问:
Learning YACC nowadays, does it make sense?
I have a huge project that is using YACC and I would need to fix a bug in it.

I might ask someone else who wrote that to fix it but I'm interested in how compilers work. Does it make sense to learn YACC nowadays? It was told me that it's old and obsolete. I would love to understand how compilers/llvm and other stuff like those work... what about YACC?

答:
I don't think YACC is obsolete. In a sense it is obsoleted by bison, the GNU implementation, but that is backward compatible with the original version.

The big compilers appear to have manually written parsers, I suppose mainly because they need better diagnostics in case of parse errors than what the generic parser generator provides. But many tools with smaller domain specific language use bison (llvm suite build-depends on bison, so it apparently has some, though clang has manually written parser), because it gets the job done quickly and in more maintainable way.


答:
Excellent communication skills.

If your colleagues cannot read your brain directly, you will need to be able to tell them what you think.  Preferrably both verbally and written.

EDIT:  A way to see them at interview time may be by asking them what their favorite framework for doing X is, and then say that they need to work on a project where X could be used, but it is a political decision to use technology Y (which is clearly older and has some limitations that X solves).

If this ends up in an argument about why the political decision is wrong, you have a strong indication of this person not doing well with pragmatic decisions.

Title: When being a technical genius is not enough to be a successful developer?

Body:
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.


问:
Is there a way to develop desktop software using PHP?
I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web.

2 reasons why they want the application to run from desktop :

So that it can work with/without internet connection

They don't want their complete data to be online

They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password.

The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL.  If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.

答:
It's possible, but it's rarely done.  PHP was designed as a language for generating HTML and its functions aren't helpful in desktop applications.

Things will be easier if you learn another language.

PHP-GTK, PHP-QT, and PHP-Wx exist but don't have any significant community.  Trying to make a deployable app will be difficult.


答:
YACC helps you with one step of the pipeline:  creating a parser for a specific grammar.  There are lots of other ways to do that step.  There are a ton of parser generators available, or you can manually write your own parser.  Depending on your requirements, there are many technical reasons to consider YACC to be obsolete, not the least of which is its limited choice of output languages.

However, it is nowhere near obsolete as a pedagogical tool.  You'll need to learn the fundamentals of parsers and grammars no matter what parser you use, and you can learn those just as easily using YACC as with anything else.  The knowledge translates very easily.  I learned YACC in school, but picked up ANTLR with very little effort.

Also consider that it's very likely your bug isn't even in the parser.  Usually most parser bugs get ironed out very early in the project, because they have a tendency to produce spectacular failures.  The more subtle errors tend to be in the layers downstream of the parser, which have nothing to do with YACC.

Title: Learning YACC nowadays, does it make sense?

Body:
I have a huge project that is using YACC and I would need to fix a bug in it.

I might ask someone else who wrote that to fix it but I'm interested in how compilers work. Does it make sense to learn YACC nowadays? It was told me that it's old and obsolete. I would love to understand how compilers/llvm and other stuff like those work... what about YACC?


答:
Java's encapsulation hierarchy is well defined:

Class -> Package -> Inheritance

"Protected" is just a weaker form of privacy than package-default as decided on by the Java designers. Access to package-default items is restricted to a subset of the entities that are allowed to access protected items.

It makes a lot of sense from a mathematical- and implementation point of view to have your sets of entities that are allowed to access things to be nested. (You couldn't nest your package-access set inside your protected-access set because classes are allowed to inherit from other packages).

It makes sense from a conceptual point of view to have something in java.util to be "friendlier" with another class in the package than something in com.example.foo.bar that is subclassing it. In the former case the classes are likely to be written by the same author, or at least coders from the same organisation.


问:
Use of Abstract Syntax Notation (ASN.1)
The problem of Electronic Data Interchange over networks is well known and understood.  Today, the most common formats for data interchange are things like XML and JSON.  There are various pros and cons of using one format over the other, and certain formats lend themselves better to certain data-sets.

I've been programming for quite some time now, and I've only just NOW come across the ASN.1 (Abstact Syntax Notation) format, which is apparently used in certain Internet protocols such as LDAP, and is actually quite old (in Internet years).  I read a bit about the format.  Like JSON, it provides primitive data types (boolean, integer, etc.) and also sequence and set types.

It's a bit different from JSON or XML in the sense that, while the notation itself is human readable, the encoding is usually not human readable (it is usually encoded in a binary format.)

Is there some reason why this format is so rarely used?  (Or am I totally wrong, and it is actually used often?) I've only just now heard of it for the first time, and I've never heard it come up in any of the various discussions I've read about the merits of JSON, YAML, XML or whatever interchange format.  Is there some major drawback to ASN.1 that prevented it from being more widely used?

答:
There are probably to main reasons why ASN.1 appears to be used so little compared to XML/JSON.

Contrary to XML (and JSON), ASN.1 is not a data interchange format, but primarily a language to define what the exchanged data means (plus a whole set of ways to encode that data). As a data definition language, ASN.1 is much more comparable to XML Schema Definitions or DTD's (Document Type Definitions). As there are a multitude of ways (both formal and informal) to define the meaning of a data interchange message, but fewer actual data interchange formats in common use, you are more likely to encounter a specific format than you are to encounter one of the formal definition methods.

As noted, ASN.1 is usually used in combination with binary interchange formats. This means that if you work in an environment that deals primarily with human-readable formats (like many of the internet protocols), you are unlikely to encounter ASN.1 definitions for the data interchange.
On the other hand, if you work in an environment that traditionally uses pure binary protocols, you might be much more familiar with ASN.1 notations.

In summary, The apparent popularity of XML/JSON over ASN.1 is partly due to comparing apples to oranges (interchange format versus definition language) and can be in part explained by cultural (programming) background.

Title: Use of Abstract Syntax Notation (ASN.1)


答:
The biggest problem with a mapped drive is that it fails utterly if someone decides to use that drive for something else. You might claim that won't happen; I might counter that claim with lots of experience and cynicism and say “Hah!”

Virtually all development tools these days are perfectly happy to work with almost everything done with relative paths. Once you use them, you should find that you can avoid committing any absolute paths to the code repository (or repositories) and everything will be much neater. The only parts that get absolute paths are things like IDE configuration files, and they're the sort of thing that it is best to leave uncommitted. (You wouldn't want to share the arrangement of tool windows? So why share the paths?)

For dependency managers, I suggest using a native one for each language. Use a good product like NuGet just for what it is good at rather than trying to wedge everything into one global magic tool. “Jack of all trades; master of none.” (Also, dependency management with C++ just isn't as advanced as with C# and Java. But you can do cooler tricks with alternative implementation bindings instead…)

For source code management, I'd advise keeping as much binary data out of the repository as possible. Only commit files that are the originals, not that are copies of something held elsewhere in the world.

Title: Using absolute paths for build dependencies

Body:
Currently we are using Source Safe and have started migration to Subversion.
All of our external SDK's(> 500 MB) are held in Source Safe right now, and I am looking for ways to move them from VSS to a repository.

We have C++ (mostly), C# (many), Java (few) projects. Hundreds of projects, all running on Windows.

I looked at a couple of dependency managers but I'm not satisfied:

NuGet - good for .Net but painful for C++

Ivy - not look in depth, but doesn't seem acceptable for C++

First question: what else should I check? It should be easy to use for a front-end developer. Best case is a simple build within the IDE.

Currently I am inclined to this solution:

Allocate some rarely used drive, like S: and declare it as 'DEV HOME'.

Then place externals here:

```<code>S:\SDK\boost\1.30\...
S:\SDK\boost\1.45\...
S:\SDK\oracle\agile_9.0.0.0\...
S:\SDK\IBM\lotus_8.0\...
S:\SDK\IBM\lotus_9.0\...
S:\Tools\NuGet\nuget.exe
S:\Tools\clr\gacutil.exe
</code>```

Autobuild machine will hold mastercopy of this 'DEV HOME'. Every developer should copy necessary SDKs from autobuild machine to local and create a 'fake' disk with subst.

I can't find any big problems with this solution:

Branches. Projects in different branches contain references to different versions of SDK (boost for example)

Version of external component will not change too frequently, so there will not be  hundreds of, say, boost versions.

Easy for developers to setup.

Absolute paths supported by any tool.

Minor problems:

Personally for me it is not beautiful solution.

Disk (S:) can be busy

Can't be done in Linux (but currently we're not interested in it)

Second question: what problems can you see with this solution?


答:
looking for a specific use case where both a subclass and a class within the same package needs to access a protected field or method...

Well to me, such a use case is rather general than specific, and it stems from my preferences to:

Start with as strict access modifier as possible, resorting to weaker one(s) only later as deemed necessary.

Have unit tests reside in the same package as tested code.

From above, I can start designing for my objects with default access modifiers (I would start with private but that would complicate unit testing):

```<code>public class Example {
    public static void main(String [] args) {
        new UnitTest().testDoSomething(new Unit1(), new Unit2());
    }

    static class Unit1 {
        void doSomething() {} // default access
    }
    static class Unit2 {
        void doSomething() {} // default access
    }

    static class UnitTest {
        void testDoSomething(Unit1 unit1, Unit2 unit2) {
            unit1.doSomething();
            unit2.doSomething();
        }
    }
}
</code>```

Side note in above snippet, Unit1, Unit2 and UnitTest are nested within Example for simplicity of presentation, but in a real project, I would likely have these classes in separate files (and UnitTest even in a separate directory).

Then, when a necessity arises, I would weaken access control from default to protected:

```<code>public class ExampleEvolved {
    public static void main(String [] args) {
        new UnitTest().testDoSomething(new Unit1(), new Unit2());
    }

    static class Unit1 {
        protected void doSomething() {} // made protected
    }
    static class Unit2 {
        protected void doSomething() {} // made protected
    }

    static class UnitTest {
        // ---> no changes needed although UnitTest doesn't subclass
        // ...and, hey, if I'd have to subclass... which one of Unit1, Unit2?
        void testDoSomething(Unit1 unit1, Unit2 unit2) {
            unit1.doSomething();
            unit2.doSomething();
        }
    }
}
</code>```

You see, I can keep unit test code in ExampleEvolved unchanged due to protected methods being accessible from the same package, even though accessing object is not a sub-class.

Less changes needed => safer modification; after all I changed only access modifiers and I did not modify what methods Unit1.doSomething() and Unit2.doSomething() do, so it is only natural to expect unit test code to continue run without modifications.

Body:
looking for a specific use case where both a subclass and a class within the same package needs to access a protected field or method...

Well to me, such a use case is rather general than specific, and it stems from my preferences to:

Start with as strict access modifier as possible, resorting to weaker one(s) only later as deemed necessary.

Have unit tests reside in the same package as tested code.

From above, I can start designing for my objects with default access modifiers (I would start with private but that would complicate unit testing):

public class Example {
    public static void main(String [] args) {
        new UnitTest().testDoSomething(new Unit1(), new Unit2());
    }

    static class Unit1 {
        void doSomething() {} // default access
    }
    static class Unit2 {
        void doSomething() {} // default access
    }

    static class UnitTest {
        void testDoSomething(Unit1 unit1, Unit2 unit2) {
            unit1.doSomething();
            unit2.doSomething();
        }
    }
}

Side note in above snippet, Unit1, Unit2 and UnitTest are nested within Example for simplicity of presentation, but in a real project, I would likely have these classes in separate files (and UnitTest even in a separate directory).

Then, when a necessity arises, I would weaken access control from default to protected:

public class ExampleEvolved {
    public static void main(String [] args) {
        new UnitTest().testDoSomething(new Unit1(), new Unit2());
    }

    static class Unit1 {
        protected void doSomething() {} // made protected
    }
    static class Unit2 {
        protected void doSomething() {} // made protected
    }

    static class UnitTest {
        // ---> no changes needed although UnitTest doesn't subclass
        // ...and, hey, if I'd have to subclass... which one of Unit1, Unit2?
        void testDoSomething(Unit1 unit1, Unit2 unit2) {
            unit1.doSomething();
            unit2.doSomething();
        }
    }
}

You see, I can keep unit test code in ExampleEvolved unchanged due to protected methods being accessible from the same package, even though accessing object is not a sub-class.

Less changes needed => safer modification; after all I changed only access modifiers and I did not modify what methods Unit1.doSomething() and Unit2.doSomething() do, so it is only natural to expect unit test code to continue run without modifications.


问:
Why is Inversion of Control named that way?
The words invert or control are not used at all to define Inversion of Control in the definitions that I've seen.

Definitions

Wikipedia

inversion of control (IoC) is a programming technique, expressed here
  in terms of object-oriented programming, in which object coupling is
  bound at run time by an assembler object and is typically not known at
  compile time using static analysis.  ~http://en.wikipedia.org/wiki/Inversion_of_control

Martin Fowler

Inversion of Control is a common pattern in the Java community that helps wire lightweight containers or assemble
  components from different projects into a cohesive application. ~ based on  http://www.martinfowler.com/articles/injection.html (reworded)

So why is Inversion of Control named Inversion of Control? What control is being inverted and by what? Is there a way to define Inversion of Control using the terminology: invert and control?

答:
This is about who controls instantiation of dependencies.

Traditionally, when a class/method needs to use another class (dependency), it is instantiated by the class/method directly. It controls its dependencies.

With Inversion of Control (IoC), the caller passed in the dependency, hence it (or a higher up caller) instantiates the dependency. The caller controls the dependencies.

The control of where a dependency is instantiated has been inverted - instead of being at the "bottom", where the code that needs it exists, it is instantiated at the "top", where the code that needs it is being called.

ContentLicense: CC BY-SA 4.0


答:
Let's say you have some sort of "repository" class, and that repository is responsible for handing data to you from a data source.

The repository could establish a connection to the data source by itself.  But what if it allowed you to pass in a connection to the data source through the repository's constructor?

By allowing the caller to provide the connection, you have decoupled the data source connection dependency from the repository class, allowing any data source to work with the repository, not just the one that the repository specifies.

You have inverted control by handing the responsibility of creating the connection from the repository class to the caller.

Martin Fowler suggests using the term "Dependency Injection" to describe this type of Inversion of Control, since Inversion of Control as a concept can be applied more broadly than just injecting dependencies in a constructor method.

Title: Why is Inversion of Control named that way?

Body:
The words invert or control are not used at all to define Inversion of Control in the definitions that I've seen.

Definitions

Wikipedia

inversion of control (IoC) is a programming technique, expressed here
  in terms of object-oriented programming, in which object coupling is
  bound at run time by an assembler object and is typically not known at
  compile time using static analysis.  ~http://en.wikipedia.org/wiki/Inversion_of_control

Martin Fowler

Inversion of Control is a common pattern in the Java community that helps wire lightweight containers or assemble
  components from different projects into a cohesive application. ~ based on  http://www.martinfowler.com/articles/injection.html (reworded)

So why is Inversion of Control named Inversion of Control? What control is being inverted and by what? Is there a way to define Inversion of Control using the terminology: invert and control?


答:
I don't think anyone can explain it better than Martin Fowler does, further down the article you linked to.

For this new breed of containers the inversion is about how they lookup a plugin implementation. In my naive example the lister looked up the finder implementation by directly instantiating it. This stops the finder from being a plugin. The approach that these containers use is to ensure that any user of a plugin follows some convention that allows a separate assembler module to inject the implementation into the lister.

As he explains in the paragraphs above that, this is not quite the same as the reason the term "Inversion of Control" originated.

When these containers talk about how they are so useful because they implement "Inversion of Control" I end up very puzzled. Inversion of control is a common characteristic of frameworks, so saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels.

The question, is what aspect of control are they inverting? When I first ran into inversion of control, it was in the main control of a user interface. Early user interfaces were controlled by the application program. You would have a sequence of commands like "Enter name", "enter address"; your program would drive the prompts and pick up a response to each one. With graphical (or even screen based) UIs the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen. The main control of the program was inverted, moved away from you to the framework.

Which is why he goes on to coin the term "Dependency Injection" to cover this specific implementation of Inversion of Control.

As a result I think we need a more specific name for this pattern. Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection.

To clarify a little: Inversion of Control means anything which inverts the control structure of a program from the classic procedural design.

In days of yore, a key example of this was letting a framework handle communication between a UI and your code, rather than leaving your code to generate the UI directly.

In more recent times (when such frameworks pretty much dominated, so the question was no longer relevant), an example was inverting control over the instantiation of objects.

Fowler, and others, decided that the term Inversion of Control covered too many techniques and we needed a new term for the specific example of instantiation of objects (Dependency Injection) but, by the time that agreement had been made, the phrase "IoC Container" had taken off.

This muddies the water a lot, because an IoC container is a specific kind of Dependency Injection, but Dependency Injection is a specific kind of Inversion of Control. This is why you're getting such confused answers, no matter where you look.


问:
LuaJit FFI and hiding C implementation details
I would like to extend an application using LuaJit FFI. Having seen http://luajit.org/ext_ffi_tutorial.html this is surprisingly easy when comparing this to the Lua C API. So far so good. However I do not plainly want to wrap C functions but provide a higher level API to users writing scripts for the application. Especially I do not want users to be able to access "primitives", i.e. the ffi.* namespace. Is this possible or will that ffi namespace be available to user's Lua scripts?

On the issue of Sandboxing Lua I found http://lua-users.org/wiki/SandBoxes which is not talking about FFI though.

Furthermore, the plan I have described above is assuming that the introduction of abstraction layers happens on the lua side of code. Is this an advisable approach or would you rather abstract functionality on the statically compiled code (on the C-side)?

答:
when you ask if "will that ffi namespace be available to user's Lua scripts?", do you care because of ease of programming, to make it harder to make a mistake, or to protect against deliberate malicious attacks?

if the last (security), then yes, you have to check about sandboxes.  it's not hard to do a reasonable one, but a real tight one is tricky.

if the others (easy to use, hard to break), then just be sure that the exported module contains only the high-level functions you want others to use.  The easiest way is to make your internal functions in local variables, and put only the "exported" functions in the table that will become your module.  (hint: don't use the module() function)


问:
Best data structure for representing English verb forms
I need to come up with a data structure to keep information about English verb forms. In most cases a verb can be in one of 4 forms: base, present participle, past participle and past simple, for example:

take

taking

taken

took

It's seemingly easy to define 4 types for each form and be over with it. However there are few exceptions that ruin this simple idea.

Present single third person form, which is in our example would be "takes".

Copular verb "to be" has multiple irregular forms in the present tense: "am", "is", "are" and "was" and "were" in the past tense

Verbs like "may" that don't inflect in the present single third person form: "she may".

What data structure would be efficient, accurate yet unambiguous for representing such information (with exceptional cases) given the following requirements have to be met:

for an arbitrary form answer the question what conjugations the form represents

for an arbitrary conjugation and a form answer the question whether the form represents the given conjugation or not?

答:
You need to consider the uses to which your data will be put. For example, if you want to do real-time deep semantic analysis of English texts or if you are trying to do machine translation of linguistic texts you will probably want to have an entry for each conjugated form that a verb can take in the language(s) of interest.

You can consider the infinitive form of a verb to be the base form and the base form should have links to all variant forms, so from the infinitive you can enumerate and access all the grammatical uses associated with the verb. Similarly, the variant forms should link back to the infinitive form.

Data structures of this type will minimize the computational load required to identify the possible grammatical uses of each verb form that you can encounter in natural language text.


答:
Binary asn.1 content is optimized for minimal data and implementation footprint. This was important in the days when embedded systems had only 2k of ram.

Today it is more important to have a human readable intuitive format.

Title: Use of Abstract Syntax Notation (ASN.1)

Body:
The problem of Electronic Data Interchange over networks is well known and understood.  Today, the most common formats for data interchange are things like XML and JSON.  There are various pros and cons of using one format over the other, and certain formats lend themselves better to certain data-sets.

I've been programming for quite some time now, and I've only just NOW come across the ASN.1 (Abstact Syntax Notation) format, which is apparently used in certain Internet protocols such as LDAP, and is actually quite old (in Internet years).  I read a bit about the format.  Like JSON, it provides primitive data types (boolean, integer, etc.) and also sequence and set types.

It's a bit different from JSON or XML in the sense that, while the notation itself is human readable, the encoding is usually not human readable (it is usually encoded in a binary format.)

Is there some reason why this format is so rarely used?  (Or am I totally wrong, and it is actually used often?) I've only just now heard of it for the first time, and I've never heard it come up in any of the various discussions I've read about the merits of JSON, YAML, XML or whatever interchange format.  Is there some major drawback to ASN.1 that prevented it from being more widely used?


答:
Here's the "regular" control flow programs usually followed:

Run commands sequentially

You maintain control over the control flow of the program

Inversion of Control "inverts" that control flow, meaning it flips it on its head:

Your program doesn't control the flow anymore. Rather than calling commands as you see fit, you wait for someone else to call you.

That last line is the important one. Rather than calling someone else when you feel like it, someone else calls you when they feel like it.

A common example of this is web frameworks such as Rails. You define Controllers, but you don't actually decide when those get called. Rails calls them when it decides there's a need.


问:
Ported Functions Licensing
I have found several functions in python 2.7.2 to be very useful and I recreated them in C++ for my own uses. How do I properly give python credit for them? Do I even have to? I never actually looked at their source codes. I just wrote functions that output the same values as the python versions of the function.</p>

答:
You don't need to give any credit if you don't want to.

Most computer languages are inspired by other languages and have features like those languages. Just check Python's own tutorial on classes and library reference for itertools. While reading these I thought they were advertising and nearly gave up reading the tutorial on classes as it was too much in the beginning.

The point is that if you want you can mention that in a comment or fill paragraphs about how you were inspired by Python but it is not necessary as you never used/saw their actual code.

OwnerDisplayName: calccrypto

Title: Ported Functions Licensing


答:
ASN.1 is actually very widely used.  Every cell phone made today uses ASN.1 Unaligned Packed Encoding Rules as part of its low level protocol.  ASN.1 is used in Aviation protocols for communications between ground and airplanes.  ASN.1 is used in communications with Satellites (as in GPS systems).  ASN.1 is used in communications between banks and in credit card transactions.  Every time you connect to a secure website using https, you are using ASN.1.  ASN.1 is used for electronic toll systems so that you don't have to stop at toll booths to pay your toll on freeways or highways.  ASN.1 is used by some shipping companies to keep track of their packages.  These some of the areas where ASN.1 is used.

It is unfortunate that it has not gotten publicity as a robust way of disparate machines with disparate operating systems and even disparate programming languages all being able to communicate with each other.

It even supports communication with XML Schema engines via the XML Encoding Rules.  The latest generation of cell phones using LTE (Long Term Evolution) heavily relies on ASN.1, so it is not going away any time soon.  It is a mature technology with a proven track record, and continues to be widely used.

Title: Use of Abstract Syntax Notation (ASN.1)


问:
If the spec is flawed, should it still be followed?
I have been assigned to develop an integration to one of my employer's applications to an external system developed by our client. Our client's specification for the integration that has some blatant flaws related to security. The flaws would allow an unauthorized user access to the system to view restricted data.

I have pointed out the flaws and their potential security risks if they are implemented as designed, and provided an alternative without the flaw, but (in short) have been told "do it the way we specified" by the client.

Does a programmer have an ethical responsibility NOT to implement code with known security risks? At what point do a client's requirements outweigh the ethical responsibility we have as software developers to create secure applications?

答:
I think you've done your part by pointing out the problem and suggesting an alternative. If they insist that you do things that expose them to a certain level of risk, you should make sure you have a paper trail (and back-ups of it) showing that they explicitly requested this, knowing the risks involved. If you're really concerned, you could tell them that you'd gladly do what they want, if they first sign some sort of legal document/disclaimer in which they acknowledge the risks associated with what they've asked you to do (and of course get a lawyer to draft such a document). I personally don't know of any precedent for such a document for this situation, but I'm sure you could find a lawyer to help you with this. If your company has a legal department, it might be something they should get involved with if there's a potential for corporate liability. And of course, if it's this serious you should discuss this with your manager as well.

I think the only situation where it might be OK to simply refuse to do the work would be if this is software for a system where the flaw that you're worried about could lead to the system being compromised in such a way that it could result in the very likely loss of life/serious personal injury or some sort of catastrophic property loss.


问:
Any ASN.1 parsers written completely in managed code & safe from buffer overflows
ASN.1 is a data format used on HTTPS certificates, and various other critical pieces of infrastructure.

I need to analyze some potentially hostile ASN.1 data, and want to ensure my code is safe from any programmer error.  I think the best way to do this is to use a managed language that does not use unsafe code.

Are there any managed implementations (C#) of an ASN.1 parser that is well tested and safe from buffer overflows.  Even better if there was a way to detect such an overflow to begin with.

答:
Please take a look at http://www.itu.int/ITU-T/asn1/links/index.htm which has an excellent list of ASN.1 tools (some commercial, some free), some of which are widely used in critical infrastructure around the world.

One of these vendors (who I work for) is OSS Nokalva (http://www.oss.com) where you can find ASN.1 Tools for C, C++, C# and Java for which you can download free trials.

Please note that just using a language like C# or Java is no guarantee against maliciously formed ASN.1 encoded messages.  Well written code and thorough enough testing can ensure that code is solid.  The wide deployment of ASN.1 software in many critical applications is a testament to how well written some ASN.1 engines are.  Note that you are more likely to find robust code from a widely used commercial ASN.1 Tool (which includes technical support) than from some of the free ASN.1 Tools which are available.


问:
Should the search engine return a dictionary or strongly typed objects?
I'm building a search engine using Lucene.NET / Solr.NET, and I'm wondering should search hits be returned as a dictionary or strongly typed object.

```<code>public class SearchResult
{
    public string SearchTerm { get; set; }
    public List<Dictionary<string, object>> SearchHits { get; set; }
    ...
}

// where search hit looks like this
Dictionary<string, object> searchHit = new Dictionary<string, object>
{
    { "Name", "John Doe" },
    { "Address", "Some street" },
};
</code>```

vs

```<code>public class SearchResult
{
    public string SearchTerm { get; set; }
    public List<Foo> SearchHits { get; set; }
    ...
}

// where search hit looks like this
var searchHit = new SearchHit
{
    Name = "John Doe",
    Address = "Some address"
};
</code>```

I will be indexing different types of objects (People, Web pages, Files, etc.).
Each object has a different set of properties (people have name and address, while web pages have URLs and titles), and search hits don't have the same set of properties as original objects (WebPage class has the MainContent property, but after indexing, the search hit that represents this object will have the PreviewText property (the first 300 characters of MainContent property with stripped HTML tags).

I don't want to duplicate the code all over the place and have: IPeopleSearchService, IWebPagesSearchService, IFilesSearchService, etc. and corresponding search results: PeopleSearchResult, FileSearchResult, etc.

```<code>interface IFooService
{
    FooSearchResult Search(string text);
    void Index(Foo foo);
    ...
}

interface IBarService
{
    BarSearchResult Search(string text);
    void Index(Bar bar);
    ...
}
...
</code>```

I would like to have a more generic solution, but I don't like over-complexity. It should be readable and easily understandable by junior developer.

```<code>interface ISearchService<TEntity, TSearchHit>
{
    SearchResult<TSearchHit> Search(string text);
    void Index(TEntity entity);
}
</code>```

How would you design such a system? Any help would be greatly appreciated!

答:
I'm not familiar with Lucene.NET / Solr.NET but it look to me that a solution for this would be to use generic types:</p>

```<code>public class SearchResult<TEntity>
{
    public string SearchTerm { get; set; }
    public List<Dictionary<string, TEntity>> SearchHits { get; set; }
    ...
}

interface ISearchService<TEntity>
{
    SearchResult<TEntity> Search(string text);
    void Index<TEntity>(TEntity entity);
    ...
}
</code>```

Body:
I'm not familiar with Lucene.NET / Solr.NET but it look to me that a solution for this would be to use generic types:

public class SearchResult<TEntity>
{
    public string SearchTerm { get; set; }
    public List<Dictionary<string, TEntity>> SearchHits { get; set; }
    ...
}

interface ISearchService<TEntity>
{
    SearchResult<TEntity> Search(string text);
    void Index<TEntity>(TEntity entity);
    ...
}


答:
Typically higher level code calls (ie, controls) lower level code. Main() calls function(), function() calls libraryFunction().

That can be inverted, so the low level library function at the bottom calls higher level functions.

Why would you do that? Middleware. Sometimes you want to control the top level and the bottom level, but there's a lot of work in the middle you just don't want to do. Take the implementation of quicksort in the C stdlib. You call quicksort at the top level. You hand qsort() a function pointer to your own function that implements a comparator on whatever you feel like. When qsort() is called, it calls this comparator function. qsort() is controlling/calling/driving your high level function.


问:
The line between ByRef Parameters and Module Variables
This question was brought up during a Standards discussion, which should revolve around SOLID Principles for Object Oriented Development.

In your experiences, have you seen benefits or drawbacks in either code readability or performance based on whether variables are passed ByRef vs Module-Level Variable?

Obviously:  If a method calls a submethod, which will not only use but also modify a parameter, it should be passed as a reference pointer (aka: ByRef).

Based on this logic, some in my discussion are very strict to never use module-level variables.

In response, I say we have a toolbox and should know when to use what tool.  For example, a sub declares a variable.  That sub calls a function, which calls a sub, which calls a function, which calls a sub, etc etc, and eventually that variable is changed 10 methods down the line.

I'd say make that variable a module level, whereas some say pass it ByRef through your tree of methods.

So where is the line when examining SOLID OOP Principles?

Do you go with an extreme?:

Never use ByRef, or Never use Module-level Variables.

Or do you set a routine depth?:

1-method, always ByRef; 2 deep, consider it;  3-depth, Module-level Variable.

Or maybe a Branching Principle?:

If, in your list of methods, the variable is really only updated in one place then passed ByRef all the way back up to the original... ByRef them all.  But if the variable is changed during multiple stages in multiple branches of the tree of methods, make it a module level.

If the latter is the case, should that also mean 20 methods down the line, ByRef all the way back up to the original is still fine?  Or maybe a hybrid of these possible rules.  What's your take on it?

答:
First off, in programming rules there are no absolutes. Every rule that is stated as an absolute has its share of exceptions.

With that out of the way, you should avoid using module-level variables as much as you should avoid global variables. Apart from the portion of the program that can access them, the two share the same problems.
Just about any advise against using global variable applies equally well to module-level variables.


问:
Average video frame size for video codec
In simple words, is it true that an average size of an encoded video frame would be FrameSize = BitRate/FrameRate? Because BitRate shows how much data we are transferring per time unit, and FrameRate shows how many frames does this time unit contain.

答:
No.

That method will generally yield very erroneous (low) results.

Video codecs generally do a LOT of compression on the video stream, as part of encoding the video.  The bit rate is of the bits AFTER encoding.


问:
What is the advantage of determining scopes statically and using them dynamically in case of Python?
Firstly let me clarify that I know C and am learning Python. So my OOPS is kind of bad.

I was reading the official tutorial and found this

Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

the innermost scope, which is searched first, contains the local names

the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names

the next-to-last scope contains the current module’s global names
the outermost scope (searched last) is the namespace containing built-in names

I understand namespaces. I think scopes are the same thing. But I couldn't figure out what does the sentence about scopes mean? What is the advantage of such an arrangement?

I understand the sentence but couldn't visualize that. So please don't say that this is problem with my English.

答:
It lets you pass around those functions which use names from the surrounding context in their behaviour.

You see this a lot when defining decorators:

```<code>def make_bold(func):
    def wrapper(*args, **kw):
        return '<b>{}</b>'.format(func(*args, **kw))
    return wrapper

@make_bold
def hello(name):
    return 'Hello {}!'.format(name)

hello('World')  # returns '<b>Hello World!</b>'
</code>```

Here the wrapper function accesses func from the parent function scope; func is a local variable in the make_bold function. wrapper is a closure; wrapper closes over func.

You can expand on this a little more by making the decorator configurable:

```<code>def format(tag):
    def decorator(func):
        def wrapper(*args, **kw):
            return '<{0}>{1}</{0}>'.format(tag, func(*args, **kw))
        return wrapper
    return decorator

@format('b')
@format('i')
def hello(name):
    return 'Hello {}!'.format(name)

hello('World')  # returns '<b><i>Hello World!</i></b>'
</code>```

Now we have two levels of scoping; tag comes from the local namespace of format(), while func is a argument for the decorator() function; both are used by wrapper().

Body:
It lets you pass around those functions which use names from the surrounding context in their behaviour.

You see this a lot when defining decorators:

def make_bold(func):
    def wrapper(*args, **kw):
        return '<b>{}</b>'.format(func(*args, **kw))
    return wrapper

@make_bold
def hello(name):
    return 'Hello {}!'.format(name)

hello('World')  # returns '<b>Hello World!</b>'

Here the wrapper function accesses func from the parent function scope; func is a local variable in the make_bold function. wrapper is a closure; wrapper closes over func.

You can expand on this a little more by making the decorator configurable:

def format(tag):
    def decorator(func):
        def wrapper(*args, **kw):
            return '<{0}>{1}</{0}>'.format(tag, func(*args, **kw))
        return wrapper
    return decorator

@format('b')
@format('i')
def hello(name):
    return 'Hello {}!'.format(name)

hello('World')  # returns '<b><i>Hello World!</i></b>'

Now we have two levels of scoping; tag comes from the local namespace of format(), while func is a argument for the decorator() function; both are used by wrapper().


问:
How can I apply Readme Driven Development to an ongoing project?
I'm assigned to a project where the goal is to update an existing software. This software was developed in a totally ad hoc manner, which means that any documentation generated is outdated, confused and just plain useless. I do not want to retroactivelly produce all the missing artifacts, since this would just be a waste of time. The code base is ugly, and really need some serious refactoring, but this is another story.

What I want is to apply Readme Driven Development to guide this project. So, basically, I want to write a Readme, which will document every change meaningful at the user level. The problem is, I have no idea about how to structure this document. For me, it's pretty clear that it should have a different layout than the traditional Readme. I really want to document changes, and not the current state of affairs.

Any ideas?

答:
While I agree with the author's assertion that you should write out a general description of what your program should accomplish before writing the first line of code or the first unit test, that's just common-sense. Figuring out what you want to do first before you actually do it is an essential component of any human endeavor.

Readme's are not structured at all; they are just text files, with no standard for creating them.  Further, authors use their readme file for different things; as a Version Description Document, an errata, things you need to know before you begin, etc.

In short, Readme-Driven Development is not a software design methodology; it is merely a clever mnemonic device the author invented to make a point.  If you're looking for an actual methodology, TDD coupled with a feature list and some design prototypes will do the job better.


问:
Why does git use hashes instead of revision numbers?
I always wondered why git prefers hashes over revision numbers. Revision numbers are much clearer and easier to refer to (in my opinion): There is a difference between telling someone to take a look at revision 1200 or commit 92ba93e! (Just to give one example).

So, is there any reason for this design?

答:
In mathematical terms:

A total order over Git's commits would be required for monotonally increasing version numbers.

Git's commits form a directed, acyclic graph (DAG) that can only be ordered partially / topologically.


问:
Is it worth writing a unit test for a DTO with the most basic getter/setters?
The advantage is it protects your DTO against future "enhancements" ?</p>

答:
Let me say, first of all, that coverage for coverage's sake is bad. Writing a unit test for your class's constructor, just to make sure that NCover or dotCover sees that the runner went through the constructor code, is worse than useless. If the test makes no assertions, then your build-bot's coverage metrics give a false sense of security. If it does make assertions, then the test will have to change if the assertions ever do, even if no other line of code will care.

Therefore, the answer to your title question is predicated on another question: Do the tests make assertions that other elements of your codebase, or your end users, will care about?

The question isn't about how basic the system under test is; a test that Add(1,2) == 3 can be useful, if that's what the code needs to do and you need to ensure it always does this. It's also useful if you're TDDing (which IMO you should be), because when you make this assertion, the code that will make it true doesn't exist yet. In TDD, no matter how simple an action may be, as long as you need a line of "end-developer code" (not built into the language or a third-party library) to perform an action, you need an assertion that proves you wrote that line of code correctly.


答:
The author of the blog post was trying to make a point about how the Agile Manifesto emphasizes "working software over comprehensive documentation", and that when you do this, you risk losing the information about how software is supposed to work.

What's needed, whether it's Waterfall, Rational Rose, Agile, or some other SDLCM, is a "statement of purpose". It is some textual description of what is to be done, and why, at a detail level fine enough in the right areas that a developer can take this description into the team room as his "requirements", and produce correctly-behaving software as a result of his development efforts, guided by whatever methodology he or his team or managers see fit to follow.

In Waterfall, this is the Requirements Document. It's all defined, in detail, up front, before development begins, and if it changes while the project is out for development, development stops and the team reverts to the "design" phase.

In UML/Rational Rose, this is a "use case narrative". It describes what the "actor" (a person in a specific business role, or an external automaton such as another program) will do that should trigger some action, and what will happen within the system as a result of this action.

In Agile, this is a "user story", the exact form of which can differ depending on the exact flavor of Agile, but the two I've seen are similar to a UML "use case narrative" and a slightly different approach: "As a... I want... so that...". Similar to a use case in that the actor and the basic action are mentioned, but the addition is an integration of the business need into the context of the story, so when designing the solution, the development team can keep the business need in mind.

None of these is a "readme", and frankly I wouldn't want to read a readme that was written in the way the blogger suggests; it will be long, it will be ordered only according to the order in which the developer added the requested features, and it will be written by a developer, who will have his own perspective on what he's adding or changing and why that may not coincide with the perspective a user would have.

Title: How can I apply Readme Driven Development to an ongoing project?

Body:
I'm assigned to a project where the goal is to update an existing software. This software was developed in a totally ad hoc manner, which means that any documentation generated is outdated, confused and just plain useless. I do not want to retroactivelly produce all the missing artifacts, since this would just be a waste of time. The code base is ugly, and really need some serious refactoring, but this is another story.

What I want is to apply Readme Driven Development to guide this project. So, basically, I want to write a Readme, which will document every change meaningful at the user level. The problem is, I have no idea about how to structure this document. For me, it's pretty clear that it should have a different layout than the traditional Readme. I really want to document changes, and not the current state of affairs.

Any ideas?