答:
Yes after normalization you still need indexing.

The tables you are working with benefit just as much as the tables you had before normalization. In actuality, on their own they're just the same: tables.

One thing you have to consider though, indexes help you find your way through your data faster. Normalizing a design of a database is always good, but sometimes for performance reason you have to denormalize the implementation. But that's only on a case by case basis.

Title: Do You Still Need Indexing After Database Normalization

Body:
After you have done a good normalization, do you still need to index the table? How is this going to affect the performance? Will it even affect the performance in some way after a good normalization?

Which columns are usually indexed if you already have the primary key and the foreign key?

It's seems like it's already effective to normalize a database. But, I might have skipped how indexing affects the database. Is this only effective when queries are used? How does this work/perform and make a database better?


问:
Unwritten rules of rewriting another team member's code
We are practicing collective code ownership. To my understanding this means that any developer can change any line of code to add functionality, to refactor, fix bugs or improve designs.

But what about a complete rewriting of code from a developer who is still in the team? Should I ask him first? What is the best practice?

答:
It probably depends on why the rewrite is necessary. If it's because there are problems with what's written, and there have always been problems with it, then talking about it is called for, if only to minimise how often code needs to be fixed in the future.

My suggestion in this case is to pair when fixing the code. This way, it provides a good example of the intermediate states, and (hopefully), some context on why the rewritten code is better. Also (if only as a personal exercise), try refactoring the code to be better without a total rewrite. It will be harder, but it's good for you.

On the other hand, there are some other times when a rewrite is called for:

The team has learned a lot since the code was written, and the dev(s) who wrote it would write it differently now, even without your input.

A new feature requirement changes the situation such that a targeted mini-rewrite is appropriate.

In these cases, I probably wouldn't bother with a conversation.

Thinking about it, it seems to me that the longer the code has been there, the less likely a conversation is necessary.

ContentLicense: CC BY-SA 3.0


问:
How can I create and manage permissions more dynamically?
I want to implement a security system into my web-based Intranet application which allows security administrators to 'fine-tune' exactly what type of access a user/role has to an object. For example, an ACL-based solution might allow a receptionist access to Create, Read and Update an appointment but not Delete it, similarly I might be able to let user Bob only Read or Comment on a company memo, but not Create, Update or Delete them.

However, how would I go about allowing a receptionist only to make appointments within opening hours? How would I restrict appointments to dates from today to one month from now? What about Bob - how would I let him Create a memo after he had gained enough 'respect' points (a bit like on here).

Crucially, how can I keep these values dynamic (opening hours, date restrictions, respect points, some new constraint) so that I don't hard-code them into the application? Can anyone recommend a method (or framework, book to read etc) so that I can let the administrator create and manage these roles and their constraints rather than the programmer?

The existing ACL and role-based systems I've seen don't seem to offer any way to deal with constraints - you either have access or you don't!

Thanks

答:
I don't know what frameworks are available for the technologies you use but as a generic solution you could use a rule based system to express and evaluate permissions.

The rules could be something like:

```<code>IF CurrentUser.IsInRole("Receptionists") AND CurrentTime.IsOpeningHour()
THEN GrantSomePermission()

IF CurrentUser.IsManager() OR (CurrentUser.IsLead() AND CurrentUser.NotInGroup("X"))
THEN DenySomething()
</code>```

The admin would need to create them. This could be either through a minimalistic language and editor or through a simple UI similar to the ones where you build queries (add conditions, group them, select operators, etc.).

The drawback of such an approach is finding the issue when something goes wrong. Debugging such rules might be tricky. Also, execution order of the rules could be a challenge.

Body:
I don't know what frameworks are available for the technologies you use but as a generic solution you could use a rule based system to express and evaluate permissions.

The rules could be something like:

IF CurrentUser.IsInRole("Receptionists") AND CurrentTime.IsOpeningHour()
THEN GrantSomePermission()

IF CurrentUser.IsManager() OR (CurrentUser.IsLead() AND CurrentUser.NotInGroup("X"))
THEN DenySomething()

The admin would need to create them. This could be either through a minimalistic language and editor or through a simple UI similar to the ones where you build queries (add conditions, group them, select operators, etc.).

The drawback of such an approach is finding the issue when something goes wrong. Debugging such rules might be tricky. Also, execution order of the rules could be a challenge.


问:
Is it a good idea to do TDD on low level components?
I'm considering writing a low level driver or OS components/kernels.

The osdev.org folks seem to think that the important bits are not meaningfully testable this way, but I have read some discussions where people thought differently. I've looked around, but have failed to find any real life examples of TDD on low-level components.

Is this something people actually do, or just something that people talk about in theory because there is not a good way to do it in practice?

答:
I don't. In my Master's embedded code I just write the code and spend my time reasoning about what it does (and doesn't). I'm not sure it could be done in my case anyway, I'm getting disturbingly close to the physical limit of memory without injecting testing code.

I think that for systems that are large enough (ie have MB of memory, not KB), it can be done for some components if you have enough time and effort. Testing pin-reading code by mocking the pins up is...er...not very meaningful. If you've separated your logic out enough, you can test the logic elsewhere.

FWIW, I don't buy TDD in the general case - it works fine for system stacks that are large enough with enough resources with enough deterministic behavior, outside of that it doesn't seem reasonable practice.

ContentLicense: CC BY-SA 2.5


问:
Type inference in Java 8
Is the introduction of the new lambda notation (see e.g. this article) in Java 8 going to require some kind of type inference?

If so, how will the new type system impact the Java language as a whole?

答:
There's a fair bit of incorrect information in ratchet freak's answer and in its comment thread. I'll respond here in an answer, since a comment is too small. Also, since this an answer after all, I'll attempt to answer the original question too. (Note however that I am not an expert on type systems.)

First, the short answers to the original question are Yes and No. Yes, Java 8 will have considerably more type inference than Java 7, and No, there is not a "new" type system in Java 8, although there are some minor changes.

Java 8 will still be statically typed, and it will still have the dichotomy between classes and interfaces. There are no new types such as function types. The type of a lambda is essentially a "functional interface" which is an ordinary interface with a single abstract method.

Interfaces can now have code in the form of default methods, but the model of single-inheritance of classes and multiple inheritance of interfaces remains the same. There are some adjustments, of course, such as rules for method resolution in the presence of default methods, but the fundamentals are unchanged.

Any type that's inferred by type inference could be written out explicitly. To use ratchet freak's example,

```<code>Collections.<MyClass>sort(list, (a, b) -> { return a.order - b.order; });
</code>```

is basically sugar for

```<code>Collections.<MyClass>sort(list,
    (Comparator<MyClass>)((MyClass a, MyClass b) -> { return a.order - b.order; }));
</code>```

So sparkleshy's statement "type inference doesn't require any extension of the type system" is basically correct.

But to return to syntactic sugar, I'll repeat my statement that a lambda expression is not syntactic sugar for an anonymous inner class. Ratchet freak stated that a lambda expression is translated into an anonymous inner class instantiation, and Sparkleshy simply reasserted that a lambda is syntactic sugar for an anonymous inner class, but these statements are incorrect. They are probably based on outdated information. Early lambda implementations did implement lambdas this way, but things have changed.

Lambda expressions are semantically different from inner classes, and they are implemented differently from inner classes.

Lambda expressions are semantically different from inner classes in a couple ways. Evaluating a lambda expression need not create a new instance each time. They also have different capture semantics, for example, they capture this differently. In an inner class, this is the inner class instance, whereas in a lambda, this is the enclosing instance. Consider the following:

```<code>public class CaptureThis {
    void a(Runnable r) { r.run(); }

    void b() {
        a(new Runnable() { public void run() { System.out.println(this); }});
        a(() -> System.out.println(this));
    }

    public String toString() { return "outer"; }

    public static void main(String[] args) { new CaptureThis().b(); }
}
</code>```

In a recent JDK 8 lambda build (I used b69), the output will be something like the following:

```<code>CaptureThis$1@113de03
outer
</code>```

Furthermore, lambda expressions are implemented completely differently from inner classes. If you compare the disassembled output, you'll see that the inner class code straightforwardly compiles to the creation and call to a constructor of CaptureThis$1, whereas the lambda expression compiles to an invokedynamic instruction that procures a Runnable through means unspecified. For a full explanation of how this works and why, see Brian Goetz' JavaOne 2012 talk Lambda: A Peek Under The Hood.

Title: Type inference in Java 8

Body:
There's a fair bit of incorrect information in ratchet freak's answer and in its comment thread. I'll respond here in an answer, since a comment is too small. Also, since this an answer after all, I'll attempt to answer the original question too. (Note however that I am not an expert on type systems.)

First, the short answers to the original question are Yes and No. Yes, Java 8 will have considerably more type inference than Java 7, and No, there is not a "new" type system in Java 8, although there are some minor changes.

Java 8 will still be statically typed, and it will still have the dichotomy between classes and interfaces. There are no new types such as function types. The type of a lambda is essentially a "functional interface" which is an ordinary interface with a single abstract method.

Interfaces can now have code in the form of default methods, but the model of single-inheritance of classes and multiple inheritance of interfaces remains the same. There are some adjustments, of course, such as rules for method resolution in the presence of default methods, but the fundamentals are unchanged.

Any type that's inferred by type inference could be written out explicitly. To use ratchet freak's example,

Collections.<MyClass>sort(list, (a, b) -> { return a.order - b.order; });

is basically sugar for

Collections.<MyClass>sort(list,
    (Comparator<MyClass>)((MyClass a, MyClass b) -> { return a.order - b.order; }));

So sparkleshy's statement "type inference doesn't require any extension of the type system" is basically correct.

But to return to syntactic sugar, I'll repeat my statement that a lambda expression is not syntactic sugar for an anonymous inner class. Ratchet freak stated that a lambda expression is translated into an anonymous inner class instantiation, and Sparkleshy simply reasserted that a lambda is syntactic sugar for an anonymous inner class, but these statements are incorrect. They are probably based on outdated information. Early lambda implementations did implement lambdas this way, but things have changed.

Lambda expressions are semantically different from inner classes, and they are implemented differently from inner classes.

Lambda expressions are semantically different from inner classes in a couple ways. Evaluating a lambda expression need not create a new instance each time. They also have different capture semantics, for example, they capture this differently. In an inner class, this is the inner class instance, whereas in a lambda, this is the enclosing instance. Consider the following:

public class CaptureThis {
    void a(Runnable r) { r.run(); }

    void b() {
        a(new Runnable() { public void run() { System.out.println(this); }});
        a(() -> System.out.println(this));
    }

    public String toString() { return "outer"; }

    public static void main(String[] args) { new CaptureThis().b(); }
}

In a recent JDK 8 lambda build (I used b69), the output will be something like the following:

CaptureThis$1@113de03
outer

Furthermore, lambda expressions are implemented completely differently from inner classes. If you compare the disassembled output, you'll see that the inner class code straightforwardly compiles to the creation and call to a constructor of CaptureThis$1, whereas the lambda expression compiles to an invokedynamic instruction that procures a Runnable through means unspecified. For a full explanation of how this works and why, see Brian Goetz' JavaOne 2012 talk Lambda: A Peek Under The Hood.


问:
How to implement classes that should be loaded once?
I'm building a little framework, currently it is just for fun. I'm wondering how should I implement classes that should be instantiated by the framework and be passed to the controller to use?

For instance: I have an "input" class that houses functions which take POST and GET data and filter it. The class is also used by the framework for routing and similar things.

Should I make these methods static? Should I use the singleton pattern? Or maybe should I make something like Codeigniter has - a loader that stores instances of all instantiated classes?

答:
what you looking for "A SINGLE instance of a class" the way to go is with a Singleton pattern.

basic implementation of a singleton pattern.

```<code>Class Test
{
    $private $testInstance;

    private function __construct() { };

    public static function getInstance();
    {
        if ($this->testInstance === null) {
            $this->testInstance = new self();
        }

        return $this->testInstance;
    }
}
</code>```

and from other place you get that class instanciated with

```<code>$test = Test::getInstance();
</code>```

every time you'll need the object you call the getInstance static method and it will return the object, or create it and return it.

hope it helps.

Body:
what you looking for "A SINGLE instance of a class" the way to go is with a Singleton pattern.

basic implementation of a singleton pattern.

Class Test
{
    $private $testInstance;

    private function __construct() { };

    public static function getInstance();
    {
        if ($this->testInstance === null) {
            $this->testInstance = new self();
        }

        return $this->testInstance;
    }
}

and from other place you get that class instanciated with

$test = Test::getInstance();

every time you'll need the object you call the getInstance static method and it will return the object, or create it and return it.

hope it helps.


问:
How does the Law of Demeter apply to object-oriented systems regarding coupling and cohesion?
How does the Law of Demeter applied to object-oriented systems with coupling and cohesion?

I was reading a book "Software development and professional practice" and came across the chapter about LoD, and was curious about how that principle is applied into object oriented systems.

答:
Coupling, simplified

When an object calls a method, property, etc. of another object we say the objects are coupled. We call it coupling because now the callee cannot change anything about its own method/prop. w.out breaking the caller.

Thus, the more the coupling - methods, props. - the harder it is to change callee code without breaking all the code that uses it.

contemplating coupling

Referencing even a single prop., method couples two objects.

Obviously coupling is necessary for creating software.

Given the 'lock step' nature of coupling we want to both limit and isolate it. This goal simply goes along with general software dev. principles.

The fewer objects we have to talk to, the lower the coupling.

If I need to make, say, 20 different method calls the coupling is lower if all 20 calls are to one class/object, vice those same methods spread over several classes/objects.

Most Knowledge causes crazy coupling

Here we have an Employee that has a Person that has a 'Address'

```<code>public class Employee {
    public Person me = new Person();
}
public class Person {
    public Address home = new Address();
}
public class Address {
    public string street;
}
</code>```

To get the street I must call: myEmployee.me.home.street. This is 180 degree opposite of the principle of least knowledge. I have to know about the internals, the composite structure, of the Employee, Person, and Address classes.

This defective class design forces me to know about all those classes and thus myEmployee.me.home.street couples me (the caller object) to no less than 3 classes - to get only a single property!

Least Knowledge Saves the Day

If I talk to only the Employee class I am applying the least knowledge principle per se, and by doing so we automatically limit coupling to only that class, and at the same time isolate coupling to that one class.

By adding all the needed properties in the Employee class we fix the coupling.

thus

```<code>public class Employee {
    public Person me = new Person();
    public string street { return me.home.street; }
}
</code>```

Allows me to call: myEmployee.street -

I "know" only Employee

I am coupled to only Employee - no matter how complex its structure.

Least Knowledge all the way down

We decoupled myEmployee from Person and Address, and ideally we should continue applying least knowledge by adding pass through properties such that Employee only talks to Person and Person only talks to Address

Body:
Coupling, simplified

When an object calls a method, property, etc. of another object we say the objects are coupled. We call it coupling because now the callee cannot change anything about its own method/prop. w.out breaking the caller.

Thus, the more the coupling - methods, props. - the harder it is to change callee code without breaking all the code that uses it.

contemplating coupling

Referencing even a single prop., method couples two objects.

Obviously coupling is necessary for creating software.

Given the 'lock step' nature of coupling we want to both limit and isolate it. This goal simply goes along with general software dev. principles.

The fewer objects we have to talk to, the lower the coupling.

If I need to make, say, 20 different method calls the coupling is lower if all 20 calls are to one class/object, vice those same methods spread over several classes/objects.

Most Knowledge causes crazy coupling

Here we have an Employee that has a Person that has a 'Address'

public class Employee {
    public Person me = new Person();
}
public class Person {
    public Address home = new Address();
}
public class Address {
    public string street;
}

To get the street I must call: myEmployee.me.home.street. This is 180 degree opposite of the principle of least knowledge. I have to know about the internals, the composite structure, of the Employee, Person, and Address classes.

This defective class design forces me to know about all those classes and thus myEmployee.me.home.street couples me (the caller object) to no less than 3 classes - to get only a single property!

Least Knowledge Saves the Day

If I talk to only the Employee class I am applying the least knowledge principle per se, and by doing so we automatically limit coupling to only that class, and at the same time isolate coupling to that one class.

By adding all the needed properties in the Employee class we fix the coupling.

thus

public class Employee {
    public Person me = new Person();
    public string street { return me.home.street; }
}

Allows me to call: myEmployee.street -

I "know" only Employee

I am coupled to only Employee - no matter how complex its structure.

Least Knowledge all the way down

We decoupled myEmployee from Person and Address, and ideally we should continue applying least knowledge by adding pass through properties such that Employee only talks to Person and Person only talks to Address


问:
Do You Still Need Indexing After Database Normalization
After you have done a good normalization, do you still need to index the table? How is this going to affect the performance? Will it even affect the performance in some way after a good normalization?

Which columns are usually indexed if you already have the primary key and the foreign key?

It's seems like it's already effective to normalize a database. But, I might have skipped how indexing affects the database. Is this only effective when queries are used? How does this work/perform and make a database better?

答: Yes.  In fact, you very well may need to pay more attention to your indexes.  Normalization is about optimal storage.  That's often at odds with retrieval speed, as more complex queries with complicated joins are used.  Sometimes people maintaining databases that require fast retrieval speeds will de-normalize, or arrange their data in slightly less normalized structures to make retrieval easier.


答:
Yes.

Indices are a method to speed up searching for the data. Some queries are by primary keys, which are usually implicitly indexed by the database engine, but other queries are likely to use other columns. Often some queries search by columns that are not even unique and thus can't become primary keys after any normalization. You will probably have to index such columns.

There is only one way to know which indices to create. Take all queries in the application, find representative example parameters for them and have the database engine show their query plans (all database engines have EXPLAIN, EXPLAIN QUERY PLAN or similar command; it is called differently in different engines) and test how long they take. Than create indices that speed up the ones that were slow. And don't forget to drop again indices that you tried but didn't help to avoid wasting resources.


问:
Branching breaks continous integration?
I think this article, A Successful Git Branching Model, is very well known among experienced DVCS users.

I use hg mostly, but I would argue this discussion is fine for any DVCS.

Our current workflow is each developer clones the master repo. We write code on our own local repo, runs tests, and if all goes well pushes to the master.

So we want to setup CI servers like Jenkins and improve our workflow with the future provisioning system (chef, puppet, ansible, etc).

Real part

Well, the model presents above works nice but branches can break CI. The feature branch should sync with the origin (according to the article, it would be development branch) to make CI and merging smooth, right?

Say Alice and Bob are working on two features. But Alice is done the next day. Bob's feature takes a week. By the time Bob is done, his changes are out of dated (maybe Alice refactored/rename some classes).

One solution is each morning developers must pull master/origin to check if there's any changes. If Alice commited, Bob should pull and merge into his workspace so his feature branch is up-to-date.

Is this a good way?

Should these branches exist in the master repo (not local clone?) Meaning should every developer has commit privilege to the master repo on GitHub/Bitbucket so they can create a new branch? Or this is done locally?

Lastly, the model presents by the article should break CI if branches are not sync with the origin/master. Since we want to do nightly build, should developers pull and merge before they leave work, and have CI runs on each feature branch as well?

答:
In response to 1)

Any way that works is a good way. However: the whole premise of Continuous Integration is to integrate continuously. The idea is to catch integration bugs not only as early as possible, but within the development feedback cycle - i.e. while all the details for the code under test are within the short-term memory of the developer making the changes. This means that, under normal, everyday circumstances, work must be integrated across feature branches on every commit - maybe once every 15 minutes or so. To reiterate: The main purpose of continuous integration is to expose integration bugs while all the details are in the short-term memory of the developer(s) making the changes.

2)

Mostly, branches are created in Mercurial by cloning repositories, so you do not need to give every developer commit privileges to the master repo. You probably, however, want to give developers the ability to create cloned repos on the continuous integration server, as it is not always feasible to run tests locally. (I once had a CI system where the unit tests took 8 hours to run on a 128 core cluster) - Needless to say, developers did not, could not run tests locally.

3)

If you have the computational resources for it, yes, developers should be fully up to date with the main line of development at all times, particularly before they leave work, and you should run overnight tests on all lines of development (Although most CI systems do not make this easy).

Title: Branching breaks continous integration?


答:
First of all, the use of feature branches (to isolate the work done on a feature) and CI (to find integration problems as soon as they are committed) are slightly at odds.

In my opinion, running CI on feature branches is a waste of time. As feature branches come and go frequently, the CI tooling would have to be reconfigured over and over again. And that for a branch that most likely only gets updates from one or two sources that coordinate their check-ins to avoid the problems a CI system is meant to detect.

Thus, there is also no point in having the feature branches on the master repository server.

As for questions 1 and 3: It is the developer's responsibility to ensure the build on the main development branch does not break when they merge their feature-branch into it. How they do that is their problem, but two possible ways are:

Pull changes made to the main development branch into the feature branch on a regular basis (e.g. daily)

When the feature is done, merge the main development branch into the feature branch and push the merge result onto the main development branch.

In either case, the obvious integration issues (e.g. renamed classes/files) are found and fixed first on the feature branch. The more subtle issues are most likely only found when the nightly build runs and should be fixed there and then.

Title: Branching breaks continous integration?

Body:
I think this article, A Successful Git Branching Model, is very well known among experienced DVCS users.

I use hg mostly, but I would argue this discussion is fine for any DVCS.

Our current workflow is each developer clones the master repo. We write code on our own local repo, runs tests, and if all goes well pushes to the master.

So we want to setup CI servers like Jenkins and improve our workflow with the future provisioning system (chef, puppet, ansible, etc).

Real part

Well, the model presents above works nice but branches can break CI. The feature branch should sync with the origin (according to the article, it would be development branch) to make CI and merging smooth, right?

Say Alice and Bob are working on two features. But Alice is done the next day. Bob's feature takes a week. By the time Bob is done, his changes are out of dated (maybe Alice refactored/rename some classes).

One solution is each morning developers must pull master/origin to check if there's any changes. If Alice commited, Bob should pull and merge into his workspace so his feature branch is up-to-date.

Is this a good way?

Should these branches exist in the master repo (not local clone?) Meaning should every developer has commit privilege to the master repo on GitHub/Bitbucket so they can create a new branch? Or this is done locally?

Lastly, the model presents by the article should break CI if branches are not sync with the origin/master. Since we want to do nightly build, should developers pull and merge before they leave work, and have CI runs on each feature branch as well?


答:
I think @aaronaught made some good points, which really leads to the answer I wanted to give, which is that it really depends on who's making the change (and why) and who wrote the code.

In my personal experience code is normally changed because either it doesn't work as intended, or you simply need to extend what it actually does.

In a Team dev environment, you shouldn't have to (and may not be able to) talk to the original coder, everything should be clear from the code.

That then leads to the question which consumes most of my time, which is what did the original programmer intend, and it is that question which most often leads to code being deleted, and is why we should comment everything, and where inexperienced junior programmers most often fall foul.

Any programmer that is changing someone else's code (refactoring) really should as a matter of courtesy and practice copy the same coding style of the code already in place, and first take steps to figure out how the original code worked, and what it was trying to, and actually going to, achieve.  Often this in itself identifys bugs, but certainly it forces people to endure the pain that the next person will have looking at your code.

In my team anyone can delete, refactor or rewrite anything, and I view 'ownership' as a practice which breeds lazyness, as if one person is sure to be notified of any changes, why would they need to make the code readable.

So in short, no, you shouldn't have to ask the original author of the code, and if on looking at the code you do, then it is a sign that either his code isn't readable enough, or you need to improve your skills.  However, I find it good form to leave the original code in place, commented out, until you're absolutely sure that in rewriting, you haven't accidentally removed required functionality.  Nobody is perfect.

Title: Unwritten rules of rewriting another team member's code

Body:
We are practicing collective code ownership. To my understanding this means that any developer can change any line of code to add functionality, to refactor, fix bugs or improve designs.

But what about a complete rewriting of code from a developer who is still in the team? Should I ask him first? What is the best practice?


答:
It is pretty simple; say A depends on B and B depends on C.
Without the Law of Demeter you can use both B and C in A but by adhering to this law, A depends only on B, it cannot depend on C.

This enables low coupling since it greatly reduces the number of dependencies of a module; cohesion, although different in concept from coupling, is achieved in the same way. By having fewer dependencies on a module, these become more specific for that module and thus increase cohesion. Also the total number of modules will rise and they will become more specialized for doing stuff specialized for the depending module (contrary to god objects) which directly translates to more coherent system.

Title: How does the Law of Demeter apply to object-oriented systems regarding coupling and cohesion?

Body:
How does the Law of Demeter applied to object-oriented systems with coupling and cohesion?

I was reading a book "Software development and professional practice" and came across the chapter about LoD, and was curious about how that principle is applied into object oriented systems.


答: I suggest make them static if you can, that is if your class doesn't have to save it's state. If it does, I think you can better make some kind of framework class that has one member of type INPUT. When you want to use the framework you instantiate a framework object, which instantiates one INPUT object. You drag that framework object everywhere you need the methods from INPUT. It's better debuggable and maintainable than a singleton. also, this: https://stackoverflow.com/a/138012/640888</p>

Title: How to implement classes that should be loaded once?

Body:
I'm building a little framework, currently it is just for fun. I'm wondering how should I implement classes that should be instantiated by the framework and be passed to the controller to use?

For instance: I have an "input" class that houses functions which take POST and GET data and filter it. The class is also used by the framework for routing and similar things.

Should I make these methods static? Should I use the singleton pattern? Or maybe should I make something like Codeigniter has - a loader that stores instances of all instantiated classes?


答:
Here is how you can do it: feature branching.

For any new task (bugfix, feature, etc) start a new branch (e.g. bugfix-ticket123-the_thingie_breaks)

While you work, continuously update and merge default (or master in git) into your feature branch. This helps you have your branch updated without having to work in the default branch

When your feature is ready and your unit tests pass, then pull and merge default into your branch once more, close your branch and push it without merging, your integrator will notice the new head and that it is a closed branch, so he/she will take care of integrating it. If you have no integrator, switch to default and merge your feature branch into default.

The important thing here is that you will have 0 conflicts in the default branch when you merge your feature branch into it, and all your tests do pass.

With this simple workflow you will always have a pristine and stable default branch, now do the same for release branches, but integrating from default. If you need to integrate hotfixes directly into the release branches you can still do this by skipping the default branch, but again, only picking branches that just updated from the target branch and have no conflicts and their unit tests pass.

Title: Branching breaks continous integration?


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

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

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

答: If the university is both requiring (via the graders) and forbidding (via IT) you to do something, then it's THEIR problem. First off, start with the graders making this request, inform them that you CAN NOT COMPLY and see what they can do. Also inform the professor (who presumably gives orders to the graders) and (if necessary) the department head. Somewhere along the line, they have to either give you a different target, or they have to let you do what they've assigned. There is no other option.</p>


问:
Intentional misspellings to avoid reserved words
I often see code that include intentional misspellings of common words that for better or worse have become reserved words:

klass or clazz for class: Class clazz = ThisClass.class

kount for count in SQL: count(*) AS kount

Personally I find this decreases readability.  In my own practice I haven't found too many cases where a better name couldn't have been used — itemClass or recordTotal.

An example from the JavaDocs for Class show this in the parameters:

```<code> public <U> Class<? extends U> asSubclass(Class<U> clazz)
</code>```

Does this show a reasonable use case?

答:
Class clazz smells like "I did not bother to try to come up with a good name". A variable is always representing something, and a good name describes that. I refuse to imagine that clazz for instance under any circumstances is the best name possible. Is it a reference to a class -> class_reference, is is a copy of a class object -> class_copy, etc. Possibly also dropping "class" and just use the descriptive word, e.g.

```<code>java.lang.SecurityManager.checkMemberAccess(Class<?> clazz, int which)
Parameters
    clazz -- the class that reflection is to be performed on.
</code>```

Here clazz is the target class that the check is to be performed on, so

```<code>checkMemberAccess(Class<?> target, int which)
</code>```

would much better describe what the parameter is used for than clazz ever will.

Body:
Class clazz smells like "I did not bother to try to come up with a good name". A variable is always representing something, and a good name describes that. I refuse to imagine that clazz for instance under any circumstances is the best name possible. Is it a reference to a class -> class_reference, is is a copy of a class object -> class_copy, etc. Possibly also dropping "class" and just use the descriptive word, e.g.

java.lang.SecurityManager.checkMemberAccess(Class<?> clazz, int which)
Parameters
    clazz -- the class that reflection is to be performed on.

Here clazz is the target class that the check is to be performed on, so

checkMemberAccess(Class<?> target, int which)

would much better describe what the parameter is used for than clazz ever will.


答:
When utilizing Singleton pattern, you also need to make __clone() private

```<code>class Single
{
    ... some code here ...
    private function __clone(){}
}
</code>```

so that you can't do something like this:

```<code>$instance = Single::getInstance();
$second = clone $instance;
</code>```

when NOT done like this, you are getting two separate instances, and if __clone() is private this will produce error

Body:
When utilizing Singleton pattern, you also need to make __clone() private

class Single
{
    ... some code here ...
    private function __clone(){}
}

so that you can't do something like this:

$instance = Single::getInstance();
$second = clone $instance;

when NOT done like this, you are getting two separate instances, and if __clone() is private this will produce error


问:
Mobile number validation
I am trying to find best way to validate a mobile number with in a country.

Currently my understanding is: User can enter whatever format they want in mobile numbers and its a waste of time and energy to validate it against a set of regular expressions.

My application is not a critical one like banking application and if the user is entering an invalid mobile number, it is at his own risk to get updates (like activate account/ do something with the application)

So I think the best way is to check for mobile number length and whether all are digits.

I want to know the best way forward and is there any good resource (non-scattered) to get all mobile number length validations based on a country code?

答:
Dealing with phone numbers it not trivial. Every country has their own specification.

Examples of variations (for each country):

The area code length can vary

The mobile phone area codes are different

The native format is different

You could of course force the usage of E.164 (+<countrycode><areacode><number>) but that doesn't feel very user friendly. You can not just strip all white spaces and just add a + and think that it's E.164. For instance Swedish phone numbers should be stripped of a leading 0 in the area code when converting to E.164.

To make a long story short: It's pointless to validate mobile phone numbers by yourself.

Options:

Send a SMS to the phone containing a code (two step validation)

Use an existing phone number library

Get the number plan for every country. (Swedens can be found here: http://www.pts.se/en-GB/Industry/Telephony/Numbering/National-numbering-and-addressing-plans/The-international-public-telecommunication-numbering-plan-E164/)

Title: Mobile number validation


问:
Default vs Impl when implementing interfaces in Java
After reading Should package names be singular or plural? it occurred to me that I've never seen a proper debate covering one of my pet peeves: naming implementations of interfaces.

Let's assume that you have a interface Order that is intended to be implemented in a variety of ways but there is only the initial implementation when the project is first created. Do you go for DefaultOrder or OrderImpl or some other variant to avoid the false dichotomy? And what do you do when more implementations come along?

And most important... why?

答:
if possible, name it after what/how it does its thing.

usually worst approach is naming it after how it is supposed to be used.

If it is supposed to be used as base class for implementation, you can use BaseX or AbstractX (if it is abstract (but try to squeze in what it does, because if it did not do anything you would not create it, you already have interface).
If it provides simplest possible functionality and it is expected to be used directly (not extending it) when such functionality suffices, you can call it SimpleX or BasicX.

If it is used unless some other implementation is provided, name it DefaultX


问:
What does SVN do better than Git?
No question that the majority of debates over programmer tools distill to either personal choice (by the user) or design emphasis, that is, optimizing design according to particular uses cases (by the tool builder). Text editors are probably the most prominent example--a coder who works on Windows at work and codes in Haskell on the Mac at home, values cross-platform and compiler integration and so chooses Emacs over TextMate, etc.

It's less common that a newly introduced technology is genuinely, demonstrably superior to the extant options.

Is this in fact the case with version-control systems (VCS), in particular, centralized VCS (CVS and SVN) versus distributed VCS (Git and Mercurial)?

I used SVN for about five years, and SVN is currently used where I work. A little less than three years ago, I switched to Git (and GitHub) for all of my personal projects.

I can think of a number of advantages of Git over Subversion (and which for the most part abstract to advantages of distributed over centralized VCS), but I cannot think of one contra example--some task (that's relevant and arises in a programmers usual workflow) that Subversion does better than Git.

The only conclusion I have drawn from this is that I don't have any data--not that Git is better, etc.

My guess is that such counter-examples exist, hence this question.

答:
Below are the two reasons that I still stay with SVN.

The learning curve. SVN is easier than Git, even the setup (server or client too), usability, and commands.

Better server packages like Subversion Edge, VisualSVN, uberSVN etc.

Title: What does SVN do better than Git?


问:
Is a coder that 'quality checks' bug fixes and bugs raised by testers a recognised role?
I've recently found myself frequently in the position where I'm checking both bug fixes by other programmers, and bugs raised by the QA team.

Any bug fixes frequently end up having 'collateral damage', and I've found it invaluable to go through any recent fixes, and analyze what other parts of the system could potentially have been impacted by the changes. It's been instrumental in maintaining the reliability of the system. Without this process, the testers generally find new bugs raised, and rarely recognize the cause as the recent bug fix.

I'm also quite often going through new bugs raised by the testers, analyzing possible causes to determine if there's a root cause that may impact on other parts of the system, quite frequently merging two or more bugs into one case. It's essentially doing the 'investigation' part of the bug fixing process, so that another programmer can focus on just the coding.

The question is, is this a recognised role? It doesn't seem to fit into the 'Programmer' or 'QA' job title neatly, it's kind of in-between. Or is the need for this role more a consequence of bad process or bad design?

答:
In just about every place that I've ever worked, these responsibilities fall to the engineer who is responsible for fixing the defect and the quality engineer responsible for ensuring that the defect has indeed been fixed and the system is still functioning as intended.

When a problem is reported (by anyone - another engineer, someone in quality, or after a deployment), it gets assigned to an engineer for investigation and resolution. This person is responsible for not just developing the solution, but for tracing from requirements through implementation and any associated automated tests to make the appropriate determination. This engineer would make sure that the defect actually is a defect and not user error, then make  the appropriate updates to some work product to address the issue. After the fix, if there was an implementation change, I would expect the engineer making the change to run through at least a basic set of tests to make sure their fix didn't introduce other problems into the system.

After an engineer has finished fixing the system, I would expect someone from quality assurance to verify that the defect has indeed been resolved and close out the defect. I would also expect that they would run other tests on the system to ensure that no other defects were injected. These would probably be more thorough or rigorous than the tests run by an engineer. If any defects were found, they would be added to the tracking system and the process would start again.

It seems to me that injecting a third person in what should be a two-person process (well, technically a three-person process, since there's probably someone that takes in the reports of issues, prioritizes them, and perhaps assigns them) just adds overhead. The investigation process of fixing a defect is crucial to actually providing a good fix for any problems, as well as maintaining (or improving) an understanding of the system. Except on the most trivial systems, I don't see how a person can just be expected to write code without a good understanding of what other modules or subsystems their code is interacting with. It's also part of professional responsibility to ensure the quality of one's work to some extent.


问:
When should the VCS history of a project be deleted?
I just refactored my project's entire codebase. So much so that even though it uses most of the same code base, things work in a radically different way. If the old version was 1.0, the new one would be 2.0. The project itself is just under 1mb in size (its a tiny little lib). I started the project a long time ago and its undergone many changes... so many that my git folder is now over 3mb in size.

In this case 3mb is a very small amount of data, but from a 'big picture' perspective, when should you cut your previous VCS history out of your current project and start over? Or should you never ever do this?

答:
My "rule of thumb" about the lifetime of version history in any kind of VCS: keep the version history alive as long as you have to maintain that specific software.

For example, I am working here with a product which is older than 10 years and maintained and evolved constantly. Our subversion repo for that product has about 500MB, but actually that is "peanuts". Having the complete log available over the whole product lifetime was often very useful to understand things which happened some time ago in the past.


答:
I would suggest that you keep entire history of git commits as they help one keep logs and maintain history of major and minor changes. But I would like to suggest forking of code to different repository once major update is released thus adding only minor updates or bug fixes to older versions and focusing majorly on new major version. </p>

<p>This help maintain a good development structure and also help one scales down the rate at which repository grows. This is the major revision management structure which is followed by many open source projects. </p>

Title: When should the VCS history of a project be deleted?

Body:
I just refactored my project's entire codebase. So much so that even though it uses most of the same code base, things work in a radically different way. If the old version was 1.0, the new one would be 2.0. The project itself is just under 1mb in size (its a tiny little lib). I started the project a long time ago and its undergone many changes... so many that my git folder is now over 3mb in size.

In this case 3mb is a very small amount of data, but from a 'big picture' perspective, when should you cut your previous VCS history out of your current project and start over? Or should you never ever do this?

Body:
I would suggest that you keep entire history of git commits as they help one keep logs and maintain history of major and minor changes. But I would like to suggest forking of code to different repository once major update is released thus adding only minor updates or bug fixes to older versions and focusing majorly on new major version.

This help maintain a good development structure and also help one scales down the rate at which repository grows. This is the major revision management structure which is followed by many open source projects.


答:
Storage is cheap, just keep it.

Sometimes you have to check if some bug was present in the pre-refactor version or reference some old piece of code.

If you really are concerned about the git checkout size then sure, you can go and delete the history, but I'd suggest starting a new repo in this case and leave the refactor commit in old one, so that when you really need it then you can easily connect them.

A git specific note: if you don't want the history for current checkout (because you just want to compile the project or create patches for current problem) you can use --depth=1, then git won't clone any history. Second thing: you can create an --orphan branch that won't share any history with other branches in repo, you can then clone only this branch and its history omitting all other objects in remote git repo.


答:
These are two roles. Both roles belong to the software change control management.

The role that pre-screens change requests is called triage. This role classifies each request as defects or enhancements, correlates with similar requests, assigns priority (or rejecting low-priority requests)

The role that reviews maintenance code changes is code review.

Title: Is a coder that 'quality checks' bug fixes and bugs raised by testers a recognised role?

Body:
I've recently found myself frequently in the position where I'm checking both bug fixes by other programmers, and bugs raised by the QA team.

Any bug fixes frequently end up having 'collateral damage', and I've found it invaluable to go through any recent fixes, and analyze what other parts of the system could potentially have been impacted by the changes. It's been instrumental in maintaining the reliability of the system. Without this process, the testers generally find new bugs raised, and rarely recognize the cause as the recent bug fix.

I'm also quite often going through new bugs raised by the testers, analyzing possible causes to determine if there's a root cause that may impact on other parts of the system, quite frequently merging two or more bugs into one case. It's essentially doing the 'investigation' part of the bug fixing process, so that another programmer can focus on just the coding.

The question is, is this a recognised role? It doesn't seem to fit into the 'Programmer' or 'QA' job title neatly, it's kind of in-between. Or is the need for this role more a consequence of bad process or bad design?


答:
There are two titles that work for this position depending on the circumstances:

Mentor Programmer:

With a new employee that is learning the ropes of your system this can be a very valuable position.  It gives you the chance to instruct on the specific code, the system as a whole, the bug reporting software, and any of the written (and unwritten) rules for working with the QA team.  As with any new employee you want to be very hands-on in the beginning and then back off once they've heard something once or twice and give them the chance to do it themselves.

Nosey Programmer:

I think we're all guilty of this at one point or another, perhaps it's slow and you need a little something extra or maybe you're working on something big and just want to do something small for a quick win, but ultimately you're sticking your nose into someone else's business.  You may be saving them time in the short term, but you're harming their overall productivity by robbing them of the chance to learn from their mistakes.  It also is going to look like you don't trust QA or the programmer to do the job correctly.

I've worked as a Support Programmer, a possible third title, but that was strictly doing bug fixes after deployment along with third party interfaces, add-on products, and anything that didn't fit neatly into a the major release development schedule.  I got really good at learning from other people's mistakes, and learning what mistakes certain programmers were likely to make over and over again. They made those mistakes because they never got the chance to learn from their own mistakes and because they knew they could rush something out the door and it would be someone else's problem if it didn't work quite right after deployment.


答:
As @victor has pointed out. rule-based authorization systems allow you to fine-tune access to your users' actions by controlling arbitrary attributes for each user.

in the ruby on rails world there is e.g. declarative_authorization that can serve as an example on how the rules interact with the roles your users have. you can take it as an example on what can be be done and how to use rule-based authorization in a MVC framework.

regarding dynamic rules:
you can read any data-source during authorization check (e.g. opening hours in a 'settings' table in your database).

NB: rule-based systems can get very complex really fast when adding rules (and/or roles). so, thorough (automated) testing is the way to go.

Title: How can I create and manage permissions more dynamically?

Body:
I want to implement a security system into my web-based Intranet application which allows security administrators to 'fine-tune' exactly what type of access a user/role has to an object. For example, an ACL-based solution might allow a receptionist access to Create, Read and Update an appointment but not Delete it, similarly I might be able to let user Bob only Read or Comment on a company memo, but not Create, Update or Delete them.

However, how would I go about allowing a receptionist only to make appointments within opening hours? How would I restrict appointments to dates from today to one month from now? What about Bob - how would I let him Create a memo after he had gained enough 'respect' points (a bit like on here).

Crucially, how can I keep these values dynamic (opening hours, date restrictions, respect points, some new constraint) so that I don't hard-code them into the application? Can anyone recommend a method (or framework, book to read etc) so that I can let the administrator create and manage these roles and their constraints rather than the programmer?

The existing ACL and role-based systems I've seen don't seem to offer any way to deal with constraints - you either have access or you don't!

Thanks


答:
You could simply add methods to your user object:

```<code>public boolean makeAppointmentsWhileOpen(Date d) {
    return this.makeAnyAppointment || isBusinessHour(d) < 30;
}

public boolean makeAppointmentFor(Date d) {
    return this.makeAnyAppointment ||
           (daysDiff(d, today) < 30);
}
public boolean createMemo() {
    return this.reputationPoints >= MIN_MEMO_POINTS;
}
</code>```

What I'm saying is that you don't need a framework to model permissions rules.  If a framework works for your needs, that's great.  If it doesn't, just add the necessary fields to your user database table or calculate permissions on-the-fly from other fields as above.

As with any permissions system, testing is critical.

Body:
You could simply add methods to your user object:

public boolean makeAppointmentsWhileOpen(Date d) {
    return this.makeAnyAppointment || isBusinessHour(d) < 30;
}

public boolean makeAppointmentFor(Date d) {
    return this.makeAnyAppointment ||
           (daysDiff(d, today) < 30);
}
public boolean createMemo() {
    return this.reputationPoints >= MIN_MEMO_POINTS;
}

What I'm saying is that you don't need a framework to model permissions rules.  If a framework works for your needs, that's great.  If it doesn't, just add the necessary fields to your user database table or calculate permissions on-the-fly from other fields as above.

As with any permissions system, testing is critical.


答: Other people have posted some pretty good answers, but what about Permissions?  Using Subversion over SSH, you can make a separate account on your server for SVN.  Different developers can be given different access to different parts of the repository.  Can GIT do that?  I guess there is gitolite, but it just doesn't seem as flexible or robust to me, nor do I know anyone who is actually using it.</p>

Title: What does SVN do better than Git?

Body:
No question that the majority of debates over programmer tools distill to either personal choice (by the user) or design emphasis, that is, optimizing design according to particular uses cases (by the tool builder). Text editors are probably the most prominent example--a coder who works on Windows at work and codes in Haskell on the Mac at home, values cross-platform and compiler integration and so chooses Emacs over TextMate, etc.

It's less common that a newly introduced technology is genuinely, demonstrably superior to the extant options.

Is this in fact the case with version-control systems (VCS), in particular, centralized VCS (CVS and SVN) versus distributed VCS (Git and Mercurial)?

I used SVN for about five years, and SVN is currently used where I work. A little less than three years ago, I switched to Git (and GitHub) for all of my personal projects.

I can think of a number of advantages of Git over Subversion (and which for the most part abstract to advantages of distributed over centralized VCS), but I cannot think of one contra example--some task (that's relevant and arises in a programmers usual workflow) that Subversion does better than Git.

The only conclusion I have drawn from this is that I don't have any data--not that Git is better, etc.

My guess is that such counter-examples exist, hence this question.


答:
Most of these answers are suggesting using the Singleton pattern or using static, but I disagree with this.  Yes, this will get the job done, but IMHO, it's a bad practice.  It's harder to test and isolate code that uses your Singleton/static code so it's not ideal.  I'd use the Inversion of Control pattern/Dependency Injection pattern.  Basically it works like this (Note that I come from a Java background):

```<code>class INeedOneInstanceOfAClass {
    OneInstanceOfAClass oneInstanceOfAClass;

    public void setOneInstanceOfAClass(OneInstanceOfAClass oneInstanceOfAClass) {
        this.oneInstanceOfAClass = oneInstanceOfAClass;
    }
    // ...
}
</code>```

Some other code is responsible for calling that setter.  The code that calls the setter makes sure it only creates one instance of OneInstanceOfAClass and it passes that same instance into all the other classes you have with a setOneInstanceOfAClass method.  As a result, there's only one instance of OneInstanceOfAClass but, OneInstanceOfAClass is not a Singleton and it doesn't need to use static anywhere.  It's just a regular class that you only instantiate once.

Now it's really easy to isolate INeedOneInstanceOfAClass in a unit test.  Your unit test creates INeedOneInstanceOfAClass and passes in a fake OneInstanceOfAClass that does whatever it needs to do to get out of the unit test's way.

Body:
Most of these answers are suggesting using the Singleton pattern or using static, but I disagree with this.  Yes, this will get the job done, but IMHO, it's a bad practice.  It's harder to test and isolate code that uses your Singleton/static code so it's not ideal.  I'd use the Inversion of Control pattern/Dependency Injection pattern.  Basically it works like this (Note that I come from a Java background):

class INeedOneInstanceOfAClass {
    OneInstanceOfAClass oneInstanceOfAClass;

    public void setOneInstanceOfAClass(OneInstanceOfAClass oneInstanceOfAClass) {
        this.oneInstanceOfAClass = oneInstanceOfAClass;
    }
    // ...
}

Some other code is responsible for calling that setter.  The code that calls the setter makes sure it only creates one instance of OneInstanceOfAClass and it passes that same instance into all the other classes you have with a setOneInstanceOfAClass method.  As a result, there's only one instance of OneInstanceOfAClass but, OneInstanceOfAClass is not a Singleton and it doesn't need to use static anywhere.  It's just a regular class that you only instantiate once.

Now it's really easy to isolate INeedOneInstanceOfAClass in a unit test.  Your unit test creates INeedOneInstanceOfAClass and passes in a fake OneInstanceOfAClass that does whatever it needs to do to get out of the unit test's way.


答:
I used work in a role called a Defect Coordinator. I was responsible for initial triage of the defects (where possible) so ones that were clearly Not Our Problem/Not A Defect didn't end up on our weekly reports to management, dishing out defects to the team (and chasing them to see what the progress was), and verifying that the fixes actually got released. I should point out that the triage was not necessarily done by the person who ends up fixing the defect; it depended on the complexity of the defect really. I know this role as an Error Manager in other organisations.

As for reviewing fixes, this fell to the team. The fixer would choose two or three relevent people in the team who could give proper feedback on the change. We used Code Collaborator to review and a link to the review would be included in the defect's report to show it had been done. The fix would not be approved for submission until the reviewers were all happy with the fix. Root Cause Analysis was also part of the process but I found that upper management did absolutely nothing with this information.


问:
Is code duplication a necessary evil in C?
I'm rather new to C, and I'm wondering if code duplication is a necessary evil when it comes to writing common data structures and C in general?

I could try to write a generic implementation for a hash map for example, but I'm always finding the end result to be messy. I could also write a specialized implementation just for this specific use case, keep the code clear and easy to read and debug. The latter would of course lead to some code duplication.

Are generic implementations a norm, or do you write different implementations for each use case?

答:
I can not speak for others, but in my own personal experience with C, code duplication has not been much of an issue.  Whether this is due to project sizes, or a charmed sample set I can not say.  However, there are three rules of thumb that I follow that I think are applicable.  In no particular order, they are ...

Write for what is needed.  Generality can come later IF it is needed.

If generality is needed, void pointers, function pointers and structure size can be invaluable.  The routine qsort(), for example, makes use of all three.

Give weight to making your code clear.


问:
What are your techniques for storing numpy structures in django database fields and how do you serialize them for http?
I want to publish a small web project that is supposed to contain some of my research results to present it to the scientific community. All my analysis I ran so far have been written in python already, thus I considered to use django web framework to provide the results. This is, because I plan to show some visualization on up-to-date data, so I can run my analysis on new data by a cron directly in django.

there are actually two questions on my mind so far, how I am going to start developing:

How can I easily store numpy arrays in sqlite to keep the structure of the array and which type of django database field suits best?

What is the best way to json.dump the numpy 2d-arrays to be able handle them in d3.js?

As you can see it is quite about putting numpy + django + d3.js together. My first hacking was to store the numpy results as strings, but I think this is not quite the best, since I need to parse them again after pulling them from database. Concerning the second question I already found simplejson.dumps but unfortunately it does not really work on numpy arrays and thus, sometimes I needed to hack something like this

```<code>return  HttpResponse('{"array1" : '+simplejson.dumps(list(array1))+'}')
</code>```

which I actually don't really like.

So to put it together again:

What are your techniques for storing numpy structures in django database fields and how do you serialize them for http?

答:
the best solution depends on a number of further questions, e.g.:

do you need to query the DB for array-content?

if yes, you will probably need to store the arrays as strings and query for strings (regex).
if no, consider serializing with cPickle. cPickle is fast and less verbose than simple strings.

anyway, you'll have to put your array in a text-field.

do you need to read or modify the arrays in python after they are written to the DB?

if yes, cPickle is the way to go. you read it back from the db, recreate the numpy array, read or modify and then encode the array as json.

if no, (and your arrays are not prohibitively big) store the array directly as json and just write the db-record verbatim to the http-respose.


答:
It's worth noting that you may not need a fully generic solution to reduce code duplication.  Sometimes ordinary refactoring and a bit of method generalization is sufficient.

When writing a generalized solution for a broad audience, you have to consider:

What novel ways might the consumer use your code, and how do you accomodate them?

What errors do I need to catch?  What errors should I not catch?

How robust does the API need to be?  How many overloads do I need to provide?

What security measures do I have to put in place, so that the code cannot be used for  evil purposes?

Eric Lippert wrote an entire article about a single design decision in the .NET framework code.  All in all, it's often simpler to just refactor.

Title: Is code duplication a necessary evil in C?

Body:
I'm rather new to C, and I'm wondering if code duplication is a necessary evil when it comes to writing common data structures and C in general?

I could try to write a generic implementation for a hash map for example, but I'm always finding the end result to be messy. I could also write a specialized implementation just for this specific use case, keep the code clear and easy to read and debug. The latter would of course lead to some code duplication.

Are generic implementations a norm, or do you write different implementations for each use case?

ContentLicense: CC BY-SA 4.0


问:
As a software architect, am I supposed to focus that much on analysing the logs and fixing other's bugs?
Since my graduation (late 2005) I was working for the same company as a c++ software engineer. A year ago I was promoted as a software architect but I have found myself involved more and more in qualification and fixing bugs, level 2 support.

50% of my time spent in Notepad++ analysing the software logs and trying to figure out what went wrong. 30% fixing other's bugs and the remaining (if any) reviewing developers spaghetti code.

I started hating this product and thinking about an exit strategy out of this company.

What do you think I can do in this situation? do you other software architect still fixing bugs in the code?

答:
The answer is probably no. Why are you spending so much time debugging and support issues? Is someone assigning that work to you?

It sounds like you need to clarify what you should be doing. You may need to fix bugs; that probably should not be the majority of your time.


答:
Your issue of reusability is not unique to C.  However, some excellent and very reusable HashMap implementations are out there which you could base yours off of.  One that's been around for a decade or two is in Java:
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

All Java collections, including HashMap are being rewritten for Java 8 to get rid of the idea of an iterator, and instead require you to pass a function to the collection so it can iterate internally.  This is a big win for writing concurrent code - the collection can manage concurrency internally so the client doesn't have to.  That said, most programmers are not used to passing function pointers.  This does a good job explaining where HashMap is headed:
http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html

The syntax of Scala may make it hard to translate something like this into C, but here's an example of a collection that already works the way the Java 8 collections will - immutable by default, providing various tranformation methods, making use of function pointers and other cool stuff like partial application:
http://www.scala-lang.org/api/current/index.html#scala.collection.Map

If you are doing a lot of stuff with HashMaps and other more advanced data structures, you might want to look at a language that supports them.

Returning to the idea of code duplication in-general, you can code really fast by cutting and pasting, but it produces terrible code.  I'd say it's acceptable in throw-away code like one-time reports.  It's also OK sometimes when there is no code down-stream of it, like UI code that just builds a screen that nothing else depends on, but really that's a very gray area at best.

I don't think it's too much of an over-simplification to say that any time you find yourself duplicating code, you should make a function.  The bugs alone that you fix in one copy of the code and not the other are enough of a reason to make a function.


答:
C makes it difficult to write generic code.  Unlike C++, which gives you templates and virtual functions, C only has 3 mechanisms for writing generic code:

void* pointers

Preprocessor macros

Function pointers

void* pointers are far from ideal, since you lose all type safety provided by the compiler, which can result in hard-to-debug undefined behavior resulting from invalid type casts.

Preprocessor macros have well-noted drawbacks - preprocessor expansion is basically just a find/replace mechanism that happens before the compilation phase, which again can result in hard-to-debug errors.  The archetypal example being something like: #define add(x) (x+x), where x can be incremented twice if you call add(i++).  You can write template-style generic code entirely using C-macros, but the result is really hideous and difficult to maintain.

Function pointers provide a good way to write generic code, but unfortunately they don't provide you with type generality - they merely provide the possibility of run-time polymorphism (which is why, for example, the standard library qsort still requires a function that takes void* pointers.)

You can also implement class hierarchies in C using structs, as is done in the GLib library which provides a generic GObject base class.  But this suffers from similar problems as using void* pointers, since you still need to rely on potentially unsafe manual casting to up-cast and down-cast.

So yeah, C makes it hard to write code that is both generic AND safe/easy-to-maintain, which unfortunately can result in code duplication.  Large C projects often use scripting languages to generate repetitive code during the build process.


答: I usually use a generic implementation, like glib's, then if the casting ends up being too annoying, make a small type-specific wrapper for it.  However, a lot of casting is expected in C, as is the use of a void* as a generic type, so what would be considered "messy" in another language is just typical C.  Scarily enough, it will look a lot more natural when you get more experience in the language.


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

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

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

答:
As long as the changes being submitted have been reviewed by the 'best programmers' anyone should be allowed submit code. The only person who should have the ability to enforce control on a repository is the Release Engineer, if that person exists.

Personally, I'd be well pissed off if I had to check in other people's code.

Some input on your edit:
No, they shouldn't. Reviews are a necessary evil, they do more good than harm and good programmers will appreciate this. Maybe there's a reluctance to participate in reviews because they don't like the idea of 'lesser programmers' criticising their code. That's just too bad. They would be far more likely to quit if the codeline is constantly buggy and they instead spend their time cleaning up after other people's half-baked submissions.


问:
how do you seperate from designing question to programming questions?
As i try to program a solution to a request arise. I can't separate the difference between implementation problems and design problems.

How do you specifically express the design problem?

答:
You can say: design is a type of implementation problem. You get a request, and sometimes it is a straightforward implementation (add X to Y, modify A, B, and C), but sometimes it requires a broader change (refactoring!) to make it straightforward. The first is an implementation problem, and the second is a design problem.

You can say: implementation is a type of design problem. You get a request, and you must design a solution. You meet some design goals (make X faster, or B more usable), and then you design the rest of it so that it works in a way that doesn't impede your design goals in the future. The second is an implementation, but the entire thing is a design problem.

You can express your design in UML or sketches/cartoons, so you can say that a design problem is something you sketch out to solve, while an implementation problem is something you write code to solve. You will want your design to be specific enough that it tells you what elements meet your requirements and goals, but not so specific that it repeats the implementation. The exact balance is tricky, depends on your audience (as in all communication), and takes time to get right.


答:
Yes. But only if you're talking about distributed source control. With centralized -- it depends.

If there are only few programmers, it takes little time. Certainly less than the fixes that will be needed to remove bugs and technical debt later.

If there are very many programmers, you can delegate the task of actual code-review to lieutenants and have the lead developer pull their changes (nearly) unquestionably. It works for Linux kernel, I don't think that there are any larger software projects...

Again, if the project is small, the lead will quickly see who gives good code and who produces bad code. He will quite quickly see that J.Random writes good code that needs only checking for architectural decisions while the intern writes bad code that needs to be reviewed line by line before merging. The feedback this way generated will reduce maintenance burden down the line and give first hand experience on whatever the intern actually learns and should be kept in company. Pulling and merging branch from other git repo takes literally a (couple) dozen seconds, usually reading the titles of commit messages will take more time, so after I know who can be trusted to write good code merging other people's code is a non-issue.

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

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

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

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


答:
Yes, review is worth it.  I'm not sure there is a productivity hit if the review process is proportional for the following reasons:

It keeps programmers honest - if you know it will be reviewed, people will take less shortcuts

It helps new programmers learn from more experience programmers

It helps transfer domain specific knowledge

Review is another gate where bugs and potential issues can be found and fixed

By not allowing all programmers to use source control they lose the ability to track changes, undo mistakes and see a reasonable history of changes.  I'm not sure you would ever want only your "best" programmers to be able to check in to git.

Having said that, I think it is reasonable that you have someone who is in charge of certain key branches, such as a release branch.  In this case I would imagine that everyone can use the git repository, but only certain people merge into the release branch.  I'm not sure there is a way to enforce this in git, but it should be possible to do by process and just checking no one else has checked into it.

Merging into the release branch could be done by the "best" programmers, or more likely done by competent people after sufficient review has taken place.


答:
I have worked at a job where check-ins were limited to team leads only (and team leads couldn't check in their own code). This served as our mechanism to enforce code reviews, largely because of a number of incidents where bad commits got into the codebase even around gated check-ins and static analysis.

On one hand, it did it's job. A number of bad commits were found before they got into the codebase (and promptly forgotten for a week or so until someone stumbled upon them). This caused less disruption in the codebase. Plus, I could push back some formatting/structure things before they became tech debt; catch some bugs before they became bugs. And it gave me a great feel for what my team was doing.

On the other hand, it caused me to spontaneously go into murderous rages when my 3 line change took 4 hours to commit because of having to track down another lead and get them to do the commit. It pushed me to do far less frequent commits than is best practice, and occasionally led to issues trying to track changes to the developer that did them.

I would not generally recommend it except in the most needing environments. Doing the reviews and commits wasn't too bad actually. Having my own process dependent on the whims of others though was infuriating. If you can't trust your developers to check in code, get better developers.


答:
No. Anyone should be able to commit.

If you have problems with bugs being committed it's not the source control policy which is wrong. It's the devs who fails to make sure that what he/she commit works. So what you have to do is to define clear guidelines on what to commit and when.

Another great thing is called unit tests ;)

There is an alternative though.

a) If you use distributed version control you can create a main repos to which only pull requests can be made. In that way all devs can get versioning of their own code while you get control of the main branch.

b) In subversion and similar you could use branches where each dev has to create patches to get it into the main branch.


答:
is the review worth the productivity hit?

It depends on team "balance" and on how reviews are set up. Both are matters of management and teamwork, no amount of version control technological magic (centralized or distributed) can have a substantial influence on that.

If done wrong, productivity hit will of course kill any benefits of the review; the answer is though not to drop idea of reviews but to find out how to do it right.

One approach to find out if your reviews are OK is to use issue tracking tool to track time spent on reviews (some code review tools allow for that, too). If you find out reviews are taking quite a lot of time, invest some effort into finding the reasons and ways to improve things. Also, it wouldn't hurt to have regular 1:1s with team members to discover potential issues with code reviews.

If "best" programmers in the team are forced to spend hours digging through incomprehensible garbage produced by crappy coders, solution is to fire crap-makers, not to appeal to VCS technology.

In one of the past projects I was assigned to review code changes done by permanently under-performing team member, in a component that took almost an hour to just build and run tests. I started reading the diffs and when I noticed an uncompilable change, I simply finished review, posted necessary comments and asked management to ensure that further review requests come with written confirmation that their code compiles. There were no "review requests" since and soon the guy left.

On the other side, when team is reasonably balanced, code reviews are fun and educative. In my prior project, we had a requirement for 100% code review and it neither took much time nor was distracting. There were bugs discovered through review, and there were debates about coding style and design choices, but that felt just... normal.

If code changes are being blocked for days... weeks from getting to QA for testing "because of reviews", studying about VCS tricks would be the least likely way to solve this problem. Instead one would better focus their effort on finding out issues in the way how review process is organized.

- Oh integration of this change was much delayed because reviewer got suddenly sick, what a misfortune.

- Hello! Hell-lo-o-o, did you ever think of having backup reviewers to deal with cases like that?


答:
Since it's not clear from your question, I just want to point out that a gatekeeper workflow is by no means required with git.  It's popular with open source projects because of the large number of untrusted contributors, but doesn't make as much sense within an organization.  You have the option to give everyone push access if you want.

What people are neglecting in this analysis is that good programmers spend a lot of time dealing with other programmers' broken code anyway.  If everyone has push access, then the build will get broken, and the best programmers tend to be the ones frequently integrating and tracking down the culprits when things break.

The thing about everyone having push access is that when something breaks, everyone who pulls gets a broken build until the offending commit is reverted or fixed.  With a gatekeeper workflow, only the gatekeeper is affected.  In other words, you are affecting only one of your best programmers instead of all of them.

It might turn out that your code quality is fairly high and the cost-benefit ratio of a gatekeeper is still not worth it, but don't neglect the familiar costs.  Just because you are accustomed to that productivity loss doesn't mean it isn't incurred.

Also, don't forget to explore hybrid options.  It's very easy with git to set up a repository that anyone can push to, then have a gatekeeper like a senior developer, tester, or even an automated continuous integration server decide if and when a change makes it into a second, more stable repository.  That way you can get the best of both worlds.


问:
shadow simulation from buildings
Is it possible to calculate shadow areas of buildings or simulate shadows of buildings in a city, using the heights of these buildings and the sun angle and azimuth?

The basic light tracing concept using trigonometry is known. However, how would one come up with simulated shadow of group of buildings in one place?

答:
Yes, this is a matter of projecting the geometry of the buildings onto a shadow plane along the sun angle, and then computing the union of the resulting polygons. This gives a single polygon that you can then get the area of by simple triangle subdivision. All of these features are actually built into your graphics card these days.

If your buildings are non-polygonal and you need a precise answer you're out of luck unless you can model them mathematically, but really that's a rare case these days--everything's built of polygons, and/or you can get away with an approximated answer.

For a specific solution, I'd recommend asking this question on Stack Overflow.

OwnerDisplayName: Yudine

Title: shadow simulation from buildings


答:
You should have a look at projects such as Gerrit which allows all developers to push their code into 'review' branch and once you senior / lead devs are happy with these changes they can push them into master/release.

If they are not happy, they can leave comments next to a line of code, ask for updated patch etc.

This way anybody with a change pending can get it out as soon as it is ready and only qualified people (with the right +2 privileges in Gerrit) will be able to push that code to test and later to production.


问:
see what ARC does?
If I understand correctly, all ARC does is automatically add memory-management statements such as retain and autorelease in the proper places in a program. Is there any way to see all the memory-management statements that ARC automatically adds to a program?

答:
You can use CFGetRetainCount to see the retain count:  </p>

```<code>CFGetRetainCount( (__bridge void*) object );
</code>```

Title: see what ARC does?

Body:
You can use CFGetRetainCount to see the retain count:

CFGetRetainCount( (__bridge void*) object );


答:
do good programmers quit if a significant portion of their job is to review other people's code?

If they are not enjoying the job and forced to do this activity, then YES. It is very likely to happen. As finding next interesting work for a good developer is not a big challenge nowadays.

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

Absolutely NO. It is for sure waste of their time, except for some critical logic which needs to be in rock-solid state.

However, junior or in-experienced developers probably should be on a probation time for a code quality, just to be on a safe side and making sure that their code follows team development guidelines, at least for couple weeks before getting privilege to commit themselves.


问:
Is there a well grounded theory on backward and forward compatibility of formats, languages, grammars and vocabularies?
I have a friend who has the specific problem of building a case against the use of a custom HTML <wrapper> tag in some site's markup. Now, intuitively we can answer that use of such a tag is risky, as future HTML specs may define a wrapper tag with semantics that conflict with its use on the site. We can also appeal to a particular section of the HTML5 spec which also recommends against the use of custom tags for this reason.

And while I agree with the conclusion, I find these arguments a little on the weak side, on their own. Is there some well grounded and proven theory in computer science from which we can derive this conclusion? Have programming language theorists created proofs about the properties of vocabulary versioning, or some such thing?

答:
There is a mechanism in XML that allows for the kind of extension that you are doing, and avoids the conflict by allocating tags in specific namespaces.  To use this, you need to use the XHTML syntax encoding of the HTML5 vocabulary. (See HTML vs. XHTML.)

What it allows you to do is to declare a namespace (which looks like a URL) and a token (e.g. "mx" for "my extension").  You need a namespace declaration at the top that associates the namespace with the token.  (See Declaring Namespaces.)

```<code> <html ...  xmlns:mx="http://mycompany/myextension" ... >
</code>```

Then, instead of defining a <wrapper> tag, you define a tag <mx:wrapper>

Because of the token, and colon, you can never conflict with an official HTML tag, because those tags are in a different namespace.  (See Namespaces of HTML5.)

What about conflicts on the token?  Remember that the "mx" is just a local identifier associated with the longer, and globally unique, namespace URL.  In another document the token "yob" might be associated with the namespace, and the tag would be <yob:wrapper> in the body of the document.

I don't know if this is the answer that you wanted, but the namespace mechanism is a well proven (if cumbersome) way to mix together tag sets from different standards bodies which necessarily work independently, but need to mix their results together into a single document.

It does require that you use XHTML, instead of HTML syntax, which actually works in most of the browsers I have experience with, in fact I generate exclusively XHTML syntax and have not had problems, but you will need to investigate whether that is suitable in your environment

Body:
There is a mechanism in XML that allows for the kind of extension that you are doing, and avoids the conflict by allocating tags in specific namespaces.  To use this, you need to use the XHTML syntax encoding of the HTML5 vocabulary. (See HTML vs. XHTML.)

What it allows you to do is to declare a namespace (which looks like a URL) and a token (e.g. "mx" for "my extension").  You need a namespace declaration at the top that associates the namespace with the token.  (See Declaring Namespaces.)

 <html ...  xmlns:mx="http://mycompany/myextension" ... >

Then, instead of defining a <wrapper> tag, you define a tag <mx:wrapper>

Because of the token, and colon, you can never conflict with an official HTML tag, because those tags are in a different namespace.  (See Namespaces of HTML5.)

What about conflicts on the token?  Remember that the "mx" is just a local identifier associated with the longer, and globally unique, namespace URL.  In another document the token "yob" might be associated with the namespace, and the tag would be <yob:wrapper> in the body of the document.

I don't know if this is the answer that you wanted, but the namespace mechanism is a well proven (if cumbersome) way to mix together tag sets from different standards bodies which necessarily work independently, but need to mix their results together into a single document.

It does require that you use XHTML, instead of HTML syntax, which actually works in most of the browsers I have experience with, in fact I generate exclusively XHTML syntax and have not had problems, but you will need to investigate whether that is suitable in your environment


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

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

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

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

答:
My first step would be to post it on any social media outlet that you use.

Twitter, Facebook, Google+, maybe even your LinkedIn profile (if you have one)

It will be the easiest avenue for word to spread out of your hands.. Post it to twitter, ask all of your friends to retweet, ask your friends to share and see what happens!

What is the project, if you don't mind me asking?


答: You say that it's very usable for others, what for? If there's a particular niche that could find use in it (computer vision, audio processing, UI, statistical analysis etc) chances are there's probably numerous forums and online or even physical communities around this. If you're part of one start there. Create a post in the forums, let people know what it does and where the project is going. If you're not part of one, join, be social, talk to other programmers. Hell, you might even find another project you want to contribute to.</p>

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

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

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

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

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


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

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

答:
I use the term Technical Debt and relate it directly to something they understand - Corporate Debt. Technical Debt is like taking out a loan. You pay interest on it. E.g., you can build a new factory and pay for it outright or you can get a loan for it. If you get a loan you will actually pay more for it in the long term, but it makes sense financially if the terms are right.

However, if you are paying 25% interest on such a loan you put yourself into a non-sustainable position. This is the same with technical debt. Sometimes it makes sense to take on some technical debt. However, there comes a point where the interest is too high and it needs to be paid off. Some techincal debt is like a home loan and some it is like credit card debt. In emergencies credit card debt is an important and valuable asset. However, it can also break the bank (or household if you choose) if used unwisely.

Another example: you can pay $10,000 for a marketing mail drop to garner more leads for sales in the future. You are paying off "sales debt". This is an expense with long term payoff. Equate this to why you would want to "spend" money now refactoring a piece of code. In both cases there is no immediate payoff, but you are setting yourself up for better performance in the future.

I tend to use the term "xxxx debt" as an analogy when talking to whomever the target audience is. E.g., Operational Debt - The printing press we have now works well, but by stopping production for one day (or one week) and upgrading to a new machine we can increase output by 25%.

EDIT - Here is another take on this


答:
In short: Your project probably needs a clean and simple explanation/introduction on what business problem does it (library/project) solve. Thus, there should be a good reason to prefer your solution over others to be picked up.

Thus, with good, clean and short explanation you may get the interest of community.

As it is mentioned, you have to spread the word about your "baby" project in social media and programmer blogs. Look to the related forums where such a specific problem is discussed or issue is not addressed yet.

Resources to look about Github sharing and managing tips:

Share your open source project via GitHub

How should I create an manage a github repository for a shared project?


答:
This person is a Reviewer, and probably a leader in their environment. On the "fixing" end, you're talking about code-review-on-steroids.  Your best programmers should be doing this task, and their advice should be treated as the golden rule by their peers.  On the "testing" end, you're talking about defect triage and trend analysis.  Only someone who has deep knowledge of your system can do this well, and their opinions should be respected by both testers and coders.

Of course, in the real world, this is scut work doled out to the lower echelons if done at all.  More's the pity.