答:
In outline it sh:ould look like:</p>

```<code>    A01-MAIN
        PEFFORM B01-PROCESS-CURSOR1
        IF OK
           PERFORM C01-PROCESS-CURSOR2
        END-IF

    B01-PROCESS-CURSOR1.
        PERFORM B02-INITIAL.
        PERFORM UNTIL SQLCODE NOT = 0
           PERFORM B03-NEXT-ROW
           PERFORM B04-INSERT-NEW
        END-PERFORM.
        PERFORM B09-CLOSE.

    .
    .
    .
    C01-PROCESS-CURSOR2.
        PERFORM C02-INITIAL.
        PERFORM UNTIL SQLCODE NOT = 0
           PERFORM C03-NEXT-ROW
           PERFORM C04-UPDATE
        END-PERFORM.
        PERFORM C09-CLOSE.

    .
</code>```

Title: Having 2 Initialize Paragraphs in 1 COBOL program

Body:
I am designing a COBOL program that does 2 things.

1 reads specific rows from a table, and inserts a new row based on the original.

2 reads different rows from the same table, and updates those rows.

Is it bad standards to have 2 initialization procedures? I need to declare 2 SQL cursors, one for each task. So I was thinking:

1 initialize cursor, 2 process, 3 initialize cursor, 4 process.

But that seems like bad logic. something is telling me it should be more like:

1 initialize cursor, 2 process But I'm having trouble thinking it out because to me, they are 2 separate tasks.

I tried to think of a way that my SQL query could do the work, and then I could just do some validation. But I'm not sure the query would be any more efficient than having a second read of the table.

Here's my structure ideas

I've added a 3rd chart that I believe follows the answer given to me on this question. Does the 3rd chart seem to me the most logical?

Body:
In outline it sh:ould look like:

    A01-MAIN
        PEFFORM B01-PROCESS-CURSOR1
        IF OK
           PERFORM C01-PROCESS-CURSOR2
        END-IF

    B01-PROCESS-CURSOR1.
        PERFORM B02-INITIAL.
        PERFORM UNTIL SQLCODE NOT = 0
           PERFORM B03-NEXT-ROW
           PERFORM B04-INSERT-NEW
        END-PERFORM.
        PERFORM B09-CLOSE.

    .
    .
    .
    C01-PROCESS-CURSOR2.
        PERFORM C02-INITIAL.
        PERFORM UNTIL SQLCODE NOT = 0
           PERFORM C03-NEXT-ROW
           PERFORM C04-UPDATE
        END-PERFORM.
        PERFORM C09-CLOSE.

    .


问:
What do you say in a code review when the other person built an over complicated solution?
The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist.

In this situation I ask "why was it done this way?"

The answer is the other person felt like doing it that way.

Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user.

The answer is no.

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done".

My view is that it is not done, it's  buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested.

An equivalent scenario is:

Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.

Again the response I get is "well it's already done."

What is an appropriate response to this attitude?

答:
One action which our team took, which dramatically improved the situation in such cases, was the move to much smaller changesets.

Instead of working on one task for a day or more and then having a (large) code review, we try to checkin much more often (up to 10 times a day). Of course this also has some drawbacks, e.g. the reviewer needs be very responsive, which decreases its own output (due to frequent interruptions).

The advantage is, that problems are detected and can be solved early, before a large amount of work in the wrong way is done.

ContentLicense: CC BY-SA 3.0


问:
Company PC refresh, laptop or desktop?
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.

答:
I've just upgraded at work too, and went down the desktop route. I was (and still am to a degree) interested in getting a laptop, mostly so I can go somewhere quiet and do some coding, but decided on a desktop for the following reasons:

Speed of processors and number of cores - gives me the ability to stand up a couple of virtuals with no problems

RAM - you can get a load of ram in a laptop, but as above, if you're running virtuals the more the merrier

Multi monitor support - I've currently got 2 monitors, and don't think I could go to 1 monitor + laptop monitor - one of my colleagues has this, but it doesn't really cut it imo. Also, I'm hoping to get 3 monitors, which isn't really available on laptop (except if you've got a usb powered monitor)

Working from home - seems to be one of the great things about laptops, but if I had one I think I'd end up working from home too often, getting too immersed in work and feeling like I need to keep the habit up - it's nice to have home for hanging out with the family & friends, as well as getting to bed at a normal time.

ContentLicense: CC BY-SA 2.5

Title: Company PC refresh, laptop or desktop?


问:
What is a dotted pair's analogy in other Lisp implementations?
What is Scheme's dotted pair construct analogous to in other Lisp implementations? I can make a vector or list quite easily, and understand those in Clojure, even though the syntax is a little different, like Clojure's vectors use square brackets [].

However, seeing a dotted pair for the first time threw me. It almost looks like it is an implementation of of map.

I'm not looking for a discussion, but more for use or the dotted pair equivalent in other Lisp dialects, like Clojure, or even Python.

答:
There's no dotted pair in Clojure.

A philosophical reason for this is that Clojure avoids the use of a concrete "pair" data structure and instead emphasises abstract "sequences" which can have may possible concrete implementations.

The closest equivalents are list and cons:

```<code>;; construct a sequence by consing a value onto any sequential object (here a vector)
(cons 1 [2 3 4])
=> (1 2 3 4)

;; construct a list
(list 1 2 3 4)
=> (1 2 3 4)
</code>```

Body:
There's no dotted pair in Clojure.

A philosophical reason for this is that Clojure avoids the use of a concrete "pair" data structure and instead emphasises abstract "sequences" which can have may possible concrete implementations.

The closest equivalents are list and cons:

;; construct a sequence by consing a value onto any sequential object (here a vector)
(cons 1 [2 3 4])
=> (1 2 3 4)

;; construct a list
(list 1 2 3 4)
=> (1 2 3 4)


答:
You were right, they were wrong :

broken YAGNI principle

broken KISS principle

is code fully tested? If no, then it is not done

What is an appropriate response to this attitude?

Do the proper code review. If they refuse to implement suggested changes without a reason, then stop wasting your time one code reviews. You can also escalate the problem to their boss.

Title: What do you say in a code review when the other person built an over complicated solution?

Body:
The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist.

In this situation I ask "why was it done this way?"

The answer is the other person felt like doing it that way.

Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user.

The answer is no.

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done".

My view is that it is not done, it's  buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested.

An equivalent scenario is:

Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.

Again the response I get is "well it's already done."

What is an appropriate response to this attitude?


答:
What do you say in a code review when the other person built an over complicated solution?

You say: "you built an overly complicated solution."

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done."

If it's too late to change anything, why are you doing a code review?


问:
When, Where, and How to Unit Test
I'm very familiar with xUnit frameworks and I try to implement unit tests on every project I start. Somewhere along the way, I realize that I'm writing the same tests over and over again, and then I run into a really difficult to test method or a test involving remote resources, and then I give up for a while. I end up coming back eagerly whenever I can to test simple things, but as soon as I run into harder things to test, I run for the hills with my tail between my legs.

Let's throw in some examples.

Long flow of things to do in a method. (How do I test this? Do I just make sure that the code's being called by stubbing things out? How should I rewrite the code to facilitate easier testing?)

```<code>public void doSomething() {
    Object1 value1 = doSomething1(this.getName());
    if (value1.isError()) {
        sendError(new Object1Error(value1.getError().getMessage()));
        return;
    }

    Object2 value2 = doSomething2(value1, this.getName());
    if (value2.isError()) {
        sendError(new Object2Error(value2.getError().getMessage()));
        return;
    }

    /* ad infinitum... */
}
</code>```

Overloaded methods and constructors.

```<code>public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}

/* test */
@Test public void testToJSON() { ... };

@Test public void testToJSONBoolean() { /* redundant similar test code... */ }
</code>```

Remote resources. How do I test that my upload API is working (ie: right request method, host, request content type, payload, etc.) without actually doing an upload? These uploads go to servers outside of my control.

```<code>public void doUpload() throws IOException {
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(...);
    putMethod.setRequestHeader(...);
    putMethod.setRequestEntity(new FileInputStreamRequestEntity(...));

    /* etc. */

    final int responseCode = client.executeMethod(putMethod);
}
</code>```

Testing server interactions with clients.

```<code>/* before we even get here, other interactions need to take place */
public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}
</code>```

Testing at first glance seems easy, until I get to these kind of situations. How do I keep my motivation for testing and write my code to be more testable?

It seems that the more things that a method needs to do, the exponentially more difficult and frustrating unit tests are to write. Do I test simply that the code is calling the right services and methods? Do I write unit tests simply to prove to myself that my code calls the methods I told it to call, or to determine that the logic is right? Help!

答:
It seems to me that you may be trying to choose your test cases based on the methods that you've already written.  This is putting the cart before the horse somewhat; it tends to lead you towards writing tests around what you ALREADY KNOW that the class does, instead of testing what it is required to do.  If there is required behaviour that you have failed to implement correctly (or at all), your unit test probably won't find it for you.

So rather than writing unit tests based on the methods that you have implemented, put your source code to one side for a moment.  Instead, write test cases based on the behaviour that your class is required to have.  Go back to the documented requirements, if you have them, and consider the different scenarios that can relate to each requirement.  Every combination of a requirement and a scenario will then give you one xUnit method.  And give your xUnit methods names that reflect the intended behaviour of your class, not the name of the method that implements that behaviour - in other words, a test method name like calculatedPriceEqualsQuantityTimesUnitPrice is so much better than testCalculatePrice.

In terms of your specific issues above -

Your doSomething method could probably do with one test method for each possible behaviour; that is, for each path through the method.

The documented requirements of your toJSON(Boolean) method will tell you how many test methods you need, and what scenario each should cover.  It's OK to have a common method in your test class, that several of these test methods would call.  There's probably no need to test toJSON() separately - its logic is really too simple to go wrong.

For remote resources and for server interactions, the trick is the same.  Bundle the code that interacts with the resource (or the server) into a single class, with no logic of its own (a "wrapper class").  The wrapper class will just pass requests straight through to the resource or the server in question, and return whatever response the resource or the server gives.  When you unit test the class that USES the resource, you should supply a mock of the wrapper class (that is, a dummy object whose behaviour you can directly control, and whose interactions get recorded so that you can verify them afterwards).  Since the wrapper class has no logic of its own, there's nothing to unit test.  However, what you can do is write a "low level integration test", which is similar to a unit test, but includes the resource that the wrapper class is wrapping.  You can usually write these in xUnit.  The purpose of such a test is to ensure that you are interacting with the resource or the server correctly; but you can usually keep the test cases very simple, because each method of the wrapper class should be very simple.

Title: When, Where, and How to Unit Test


问:
How important is an SSL certificate for a website?
I'm bootstrapping my own project, it has a registration/login area (via devise with RoR, properly hashed and salted of course). As I'm using subdomains and I need to access them with iframes (it's justified, really!) I'd need one of those expensive certificates that cover subdomains.

As I'm doing this out of my own time and money, so I'm hesitant to drop a couple of hundreds on a certificate, plus a couple of hours delving into something I haven't tried before. I'm not storing any sensitive information besides the email address and the password. As far as I understand, the only vulnerability happens when a user logs or signs up from an unencrypted network (such as a coffee shop) and someone is listening the network.

Am I being cheap? Is this something I should tackle before releasing into the wild. I probably should mention I have 25,000 users signed up to be notified when I launch, so I'm nervous about it.

答: I'd buy one. The cost of the certificate is not that big considered the level of trust it provides to the users. Think of it as an investment. If your applications don't seem to be secure (and properly signed SSL certificates give assumption that a website is secure) people may lose interest in using your future products. </p>


答:
"It is already done" is not a satisfying answer. Done means tested and working. Every extra code that is not doing anything useful should be maintained the proper way (deleted).

Assign him this task again asking to refactor and optimize his solution. If he doesn't do that, assign him a pair programmer and hope he'll learn something from the colleague.


问:
How much design happens in your implementation phase?
For those of you who work in big-design-up-front/waterfall groups: how much critical thinking and design is skipped in your design phase and left to your implementation phase? How complete and detailed are your functional and technical specifications delivered at the end of the design phase?

It seems to me that there's a lot of room for interpretation in the level of detail that needs to be provided at the end of the Design phase, and it irks me when the design phase is rushed and then managers get angry that the build phase doesn't progress like we're churning out widgets on an assembly line. On the other hand, a design phase that's complete enough to make the build phase operate like an assembly line practically includes the implementation phase with it - all that would be left in "build" is to type stuff into the editor. Of course, it also means your design phase is gigantic.

I realize that this is a shortcoming of the waterfall model, but if there's anyone out there that can provide some constructive advice: Where does one draw the line? What should the expectations for the design and build phases be, and what kinds of design shortcomings or mistakes should/shouldn't be tolerated in the build phase?

答:
i'm a huge fan of rapid prototyping, rapid incrementation, and rapid iteration. evolution rather than "intelligent design". you're writing software to solve problems for people and people tend to change their minds and needs over time, even short periods of time.

it's nice to get requirements, a birds-eye view, and "sign off" as squared-away as possible before coding, but there is little point being dogmatic, its all fluid. be prepared to edit, amend, and throw away code as you go. the funny thing is you never arrive at a completion point anyway...most code seems to change while people care about it, and then once no one cares, it just gets deleted.

now to be certain this won't apply to must-work-the-first-time bits of software like aircraft control systems, nuclear reactor controls etc, but my guess is that isn't your case.


答:
You should focus on the root cause of the problem:

Education of programmers focuses on increasing complexity given to programmers. Ability to do this was tested by the school. Thus many programmers will think that if they implement simple solution, they did not do their job correctly.

If the programmer follows the same pattern he has done hundreds of times while at the university, it's just how programmers are thinking -- more complexity is more challenging and thus better.

So to fix this you'll need to keep strict separation of what your company requirements are relative to complexity compared to what is normally required in programmer's education. Good plan is a rule like "highest complexity level should be reserved only for tasks designed to improve your skills - and it shouldn't be used in production code".

It will become a surprise to many programmers that they are not allowed to do their craziest designs in the important production code environment. Just reserve time for the programmers to do experimental designs, and then keep all the complexity in that side of the fence.

(in code review it's already too late to change it)


问:
Why aren't design patterns added to the languages constructs?
Recently I was talking with a colleague who mentioned that his company was working on adding the MVC design pattern as a PHP extension.

He explained that they wrote C code for adding Controllers, Models and Views to the language constructs to increase performance.

Now I know that MVC is an architectural design pattern that is used widely in web applications, but I still have to come across languages that have a language construct for Controllers for example.

IMHO integrating design patterns into a language can emphasize the importance of good OO design.

So, Why aren't the most used design patterns (MVC, Factory, Strategy,...etc.) added to the language constructs?

If the question sounds too broad then you may limit the question to PHP only.

Edit:

I'm not implying that one must use a design pattern when developing a project. Actually I promote the methodology of keep it simple as long as it works.

答:
Some of them are. For example iterators are language feature in many languages and their standard libraries (hi there, foreach and yield return). Observer is also frequently present in form of events (not in PHP - you have to manage callback subscription yourself). Command is core feature in WPF.

Many of the others wouldn't really benefit from language support (and would make the language more cumbersome) - how would you simplify Controllers if you could design language feature for them? As classes, they benefit from all the infrastructure already present to support classes - you can instantiate them, pass them around and for example unit test them as any other object.

The only component of MVC which IMO could benefit from some sort of language support is View (with some official templating engine) - and it in PHP already kind of is supported - you are able to dynamically create and load PHP scripts (which are often with some kind of preprocessing used as templates).

The same applies for factory method - how would you simplify that, if you could have any kind of language feature you wanted? One feature which some languages (such as C++) lack is ability to construct object from this type name, but most higher level languages can do this (and it is not even necessary to create useful factory methods). Other than that, all you need is to be able to create a method which instantiates and returns and object.


答:
Because design patterns are implemented perfectly well with user code. His example only happened because it's PHP- but if you actually needed performance, you'd just work in another language or get HipHop or something.

Language features are complicated, both to specify and to implement, and it's not justifiable to create one for the sole purpose of "The current idioms are X". You'd barely save any meaningful user code at all, and for nothing.

Title: Why aren't design patterns added to the languages constructs?

Body:
Recently I was talking with a colleague who mentioned that his company was working on adding the MVC design pattern as a PHP extension.

He explained that they wrote C code for adding Controllers, Models and Views to the language constructs to increase performance.

Now I know that MVC is an architectural design pattern that is used widely in web applications, but I still have to come across languages that have a language construct for Controllers for example.

IMHO integrating design patterns into a language can emphasize the importance of good OO design.

So, Why aren't the most used design patterns (MVC, Factory, Strategy,...etc.) added to the language constructs?

If the question sounds too broad then you may limit the question to PHP only.

Edit:

I'm not implying that one must use a design pattern when developing a project. Actually I promote the methodology of keep it simple as long as it works.


答:
Why aren't the most used design patterns (MVC, Factory, Strategy,...etc.) added to the language constructs?

Most of these patterns can implemented in most programming languages without specific linguistic support.  Take for instance MVC in Java:

You can code it directly.

You can implement it using an application generator ... and take care of a whole lot of other boilerplate at the same time.

You can implement it using "framework" library classes.

You can implement it using annotations and static or runtime annotation processing.

Given all of these options, there is little value in directly extending the language.  And there are a number of "downsides":

It would tend to clutter up the language syntax, (arguably) making life harder for novice programmers.

It would tend to make the language specification larger and more complex, making it harder for language implementors.  (And, of course, the larger the spec is, the more likely that there will be errors and inconsistencies.)

There will always be pressure to add yet another pattern ... leading to issues / concerns with language stability.

By supporting specific patterns in the language, you hard wire specific ways of supporting the patterns, which may not suit some applications.


答:
It would be wise to buy one. As mentioned, it is ALL about end user trust to your website.

so I'm hesitant to drop a couple of hundreds on a certificate - well it is not expensive and you may get one under $50.

SSL - is really important to secure your site and add a level of confidence to the visitors in your site. In regards to the login process, why NOT to use OAuth ?
This feature will skip the user hassle to spend time in registration for your website. Website user traffic will really benefit from that. Seriously!, find some time to research it.

A good reference on common SSL questions - All about SSL Certificates

Title: How important is an SSL certificate for a website?

Body:
I'm bootstrapping my own project, it has a registration/login area (via devise with RoR, properly hashed and salted of course). As I'm using subdomains and I need to access them with iframes (it's justified, really!) I'd need one of those expensive certificates that cover subdomains.

As I'm doing this out of my own time and money, so I'm hesitant to drop a couple of hundreds on a certificate, plus a couple of hours delving into something I haven't tried before. I'm not storing any sensitive information besides the email address and the password. As far as I understand, the only vulnerability happens when a user logs or signs up from an unencrypted network (such as a coffee shop) and someone is listening the network.

Am I being cheap? Is this something I should tackle before releasing into the wild. I probably should mention I have 25,000 users signed up to be notified when I launch, so I'm nervous about it.


答:
So then I suggest that he delete all the unnecessary complexity.  The answer I usually get is "well it's already done".

That is not an acceptable answer:

If it is really too late to change, then the code review wss largely a waste of time, and management needs to know this.

If that's really a way of saying "I don't want to change", then you need to take the position that the extra complexity is BAD for the codebase BECAUSE of the problems / cost it is going to incur later.  And reducing the potential for future problems the real reason you are doing the code review in the first place.

And ...

... the solution wasn't fully functional ...

That is quite possibly a direct result of the unnecessary complexity.  The programmer has made it so complex that he no longer fully understands it and / or he has wasted his time implementing his complexity rather than the function points.  It would be worth pointing out to the programmer that cutting out the complexity may actually get him to a working program faster.

Now, it sounds like you don't have the power (or maybe the confidence) to "push back hard" on this.  But even so, it is worth making a bit of noise about this (without personalizing it) in the hope that the offending coder will do a better job ... next time.

What is an appropriate response to this attitude?

Ultimately, bring it to management's attention ... unless you have the power to fix it yourself.  (Of course, this won't make you popular.)


答:
They are.

Functions were a design pattern in assembly code before they became a language construct in C.

Virtual functions were a design pattern in C before they became a langiage construct in C++.

However, there's a trade off. If the pattern involves production of boilerplate code (even a couple of keywords), that's an indication it would be a useful language feature. But if the pattern is simple and clear, eg. C's "for (int i=0;i<10;i++)", it's still useful for everyone to write it the same way, but it's not significantly longer than "for i = 0 to 10" and has the significant advantage that it's obvious how to alter it to make a slightly different loop.


答:
It's all about the users, they do not provide any kind of security, the certificates are just products to sell.

You may want to take a look at this

http://en.wikipedia.org/wiki/Comparison_of_SSL_certificates_for_web_servers


答:
Design Patterns are added to language constructs all the time. Ever heard of the Subroutine Call Design Pattern? No? Me neither. That's because Subroutine Calls, which were a Design Pattern in the early 1950s got added to languages pretty much instantly. Nowadays, they are even present in the machine code instruction sets of CPUs.

What about the For Loop Design Pattern? The While Loop Design Pattern? The Switch Design Pattern? The Object Design Pattern? The Class Design Pattern? All of these have been added to some languages.


答:
Whenever you hit a difficult-to-test method, it's highly likely that method does too much. Look at this example you gave:

```<code>public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}
</code>```

This is doing more than simply updating the client profile. What this method should actually be called is validateProfileAndUpdateIfValidThenEmailUserAndServeView(). This should be your clue that the method is doing too much.

Now you can have this method, but you need to abstract out the different components.

```<code>private ValidationService validator; // inject these however you choose
private EmailerService emailer;
private UserProfileRepository users;

public UserClientView processClientUpdateRequest(UserProfile profile) {
    if (!validator.validateUser(profile)) {
        return new FailureUserClientView(profile);
    }

    users.add(profile);
    emailer.notifyUserOfProfileChange();

    return new SuccessUserClientView(profile);
}
</code>```

See how much easier this is to test now?

You can, for example, stub out your repository and your emailer with objects that do nothing, mock out the validator you can test all of these methods separately) and simply test the validation logic (i.e. the type returned by the method is based on the response from validateUser).

That's two tests.

Add another two to check that, if the validator responds positively, the DB is called and the emailer notified and you're largely done with this method. You still have the emailer and validation services to test (the repository should be a very thin layer to the database, thus shouldn't benefit from unit testing), but each one individually is much easier to handle than the method you gave yourself.

This is the entire principle behind TDD -- write the tests first and you figure this stuff out much earlier, before you've started developing the method itself. You see very quickly that the name of the method is not descriptive and if you make it descriptive then it indicates a method that does too much.

Note, the only problem you describe that isn't solved by mocking and stubbing services is the overloaded method.

Now this is a very different issue. This is when testing becomes dogmatic and becomes more of a hindrance than a benefit. Give your example:

```<code>public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}
</code>```

As long as the latter method is tested, you're fine. Writing tests for the outer method is not going to change your design at all, nor is it going to highlight a regression bug later. Thus it serves no purpose.

Title: When, Where, and How to Unit Test

Body:
I'm very familiar with xUnit frameworks and I try to implement unit tests on every project I start. Somewhere along the way, I realize that I'm writing the same tests over and over again, and then I run into a really difficult to test method or a test involving remote resources, and then I give up for a while. I end up coming back eagerly whenever I can to test simple things, but as soon as I run into harder things to test, I run for the hills with my tail between my legs.

Let's throw in some examples.

Long flow of things to do in a method. (How do I test this? Do I just make sure that the code's being called by stubbing things out? How should I rewrite the code to facilitate easier testing?)

```<code>public void doSomething() {
    Object1 value1 = doSomething1(this.getName());
    if (value1.isError()) {
        sendError(new Object1Error(value1.getError().getMessage()));
        return;
    }

    Object2 value2 = doSomething2(value1, this.getName());
    if (value2.isError()) {
        sendError(new Object2Error(value2.getError().getMessage()));
        return;
    }

    /* ad infinitum... */
}
</code>```

Overloaded methods and constructors.

```<code>public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}

/* test */
@Test public void testToJSON() { ... };

@Test public void testToJSONBoolean() { /* redundant similar test code... */ }
</code>```

Remote resources. How do I test that my upload API is working (ie: right request method, host, request content type, payload, etc.) without actually doing an upload? These uploads go to servers outside of my control.

```<code>public void doUpload() throws IOException {
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(...);
    putMethod.setRequestHeader(...);
    putMethod.setRequestEntity(new FileInputStreamRequestEntity(...));

    /* etc. */

    final int responseCode = client.executeMethod(putMethod);
}
</code>```

Testing server interactions with clients.

```<code>/* before we even get here, other interactions need to take place */
public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}
</code>```

Testing at first glance seems easy, until I get to these kind of situations. How do I keep my motivation for testing and write my code to be more testable?

It seems that the more things that a method needs to do, the exponentially more difficult and frustrating unit tests are to write. Do I test simply that the code is calling the right services and methods? Do I write unit tests simply to prove to myself that my code calls the methods I told it to call, or to determine that the logic is right? Help!

Body:
Whenever you hit a difficult-to-test method, it's highly likely that method does too much. Look at this example you gave:

public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}

This is doing more than simply updating the client profile. What this method should actually be called is validateProfileAndUpdateIfValidThenEmailUserAndServeView(). This should be your clue that the method is doing too much.

Now you can have this method, but you need to abstract out the different components.

private ValidationService validator; // inject these however you choose
private EmailerService emailer;
private UserProfileRepository users;

public UserClientView processClientUpdateRequest(UserProfile profile) {
    if (!validator.validateUser(profile)) {
        return new FailureUserClientView(profile);
    }

    users.add(profile);
    emailer.notifyUserOfProfileChange();

    return new SuccessUserClientView(profile);
}

See how much easier this is to test now?

You can, for example, stub out your repository and your emailer with objects that do nothing, mock out the validator you can test all of these methods separately) and simply test the validation logic (i.e. the type returned by the method is based on the response from validateUser).

That's two tests.

Add another two to check that, if the validator responds positively, the DB is called and the emailer notified and you're largely done with this method. You still have the emailer and validation services to test (the repository should be a very thin layer to the database, thus shouldn't benefit from unit testing), but each one individually is much easier to handle than the method you gave yourself.

This is the entire principle behind TDD -- write the tests first and you figure this stuff out much earlier, before you've started developing the method itself. You see very quickly that the name of the method is not descriptive and if you make it descriptive then it indicates a method that does too much.

Note, the only problem you describe that isn't solved by mocking and stubbing services is the overloaded method.

Now this is a very different issue. This is when testing becomes dogmatic and becomes more of a hindrance than a benefit. Give your example:

public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}

As long as the latter method is tested, you're fine. Writing tests for the outer method is not going to change your design at all, nor is it going to highlight a regression bug later. Thus it serves no purpose.


答: What I have said in the past is "this code is complex and I am not confident in what it is trying to do, is it possible to either simplify it or write it more clearly?"</p>


答:
Some design patterns are indeed added as language constructs - they just don't get identified as such because people start regarding them as "syntax" once they are built in. Exception handling in Java is a good example - many people would code something similar explicitly as a design pattern if it wasn't part of the core syntax.

But to focus on the question - there are many reasons why you would not want to add too many design patterns to a language:

It isn't necessary to add them as language constructs - all design patterns can be implemented in other ways

It would complicate the language - this is a bad idea as it makes the language harder to learn, makes compilers and tools more difficult to write

Alternative implementation approaches exist for many design patterns. Choosing one approach and blessing it as part of the core language would probably lead people to use that approach over others (which might be much better in some circumstances)

Over-reliance on design patterns is probably a bad idea in any case - language designers probably realise that they shouldn't be encouraging them even further.

Also, if you use a sufficiently powerful language with metaprogramming capabilities (e.g. a Lisp), it becomes relatively straightforward to extend the language yourself to implement any design pattern. You don't need any patterns at all in the core language if it is easy to add your own with a 5-line macro.


答:
Read the 'gang of four' book and it'll become clear that:

Design patterns in the book are actually well known smalltalk conventions encoded in other OO languages.

As such, those patterns cannot be included to the OO language -- it would be reimplementing smalltalk inside those languages -- it's better to use smalltalk directly

Why design patterns are useful is because they de-emphasize the role of the currently used language, and focuses on other issues than syntax. Encoding those patterns inside the language would lose this feature of the design patterns.

The real problem in the above question is that it misses the point that writing software is not only about learning the language. It's important to take sufficient distance from what language is directly providing and focus on current requirements.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: In the Visual Studio editor, most of the places we deal with non-English bugs are in comments, and they are most east-Asian languages (Input Method Editor (IME) related). I'm pretty sure I just saw one the other day where right-to-left text in comments displays incorrectly in quick info or parameter help, so there are certainly people doing it :)</p>


答:
If you are "only" gathering e-mails and passwords you maybe want to try creating your own certificate OpenSSL (http://www.openssl.org/) before committing any funds.

But...

This is just something you can do to "try things out" because website users will get a warring as this will not be a recognized/accepted certificate.

My advise is to invest in SSL, simply because email and passwords are a very sensitive private data that can lead to other kind of exposures (say I use the same pass for my email account - if this info leaks out, then all e-mail data is exposed, including CC data, any and all access info I have for other online services and god knows what else...)

We need a secure and trustworthy WEB and few dozen bucks is a small price to pay for user security. (even as basic as SSL)


问:
Java BufferedReader vs Separate Producer consumer thread
I have a very big file delimited by some sequence of characters '*L*I*N*E'. The file will be of the order of 250G. And each line comes around 600bytes to 1000 bytes. I will be performing the following operations on the file,

Read the file line by line and for each line, I will be giving it to a parser which will do some calculation on the line and update some stats. The parser will take roughly 15 micros per line.

As of now I am using the BufferedReader to read the lines and pass it over to the parser in a single thread. My question is if I have a separate reader thread which only reads the file and dump everything in a queue (in memory) and have my parser act on the in-memory queue(in a separate consumer thread), can I achieve better throughput?

Nothing changes except that my parser acts on the inmemory data and another thread takes only IO operation(read the file and dump in a queue).

It is a complex piece of software in which the above is one part, so I am trying to speed up the above part. Hence I can't able to post the actual code.

答:
250G split by 600 bytes to 1000 bytes gives you about 250.000.000 lines. Spending 15 microseconds at parsing these will take 3750 seconds ie about an hour (one hour is 3600 seconds).

About an hour would be the time spent on parsing in between execution of reader code in same thread.

To estimate throughput gain I'd next benchmark single threaded version. To save time I'd likely benchmark with smaller size file, like 2.5G (timing would have to be multiplied by 100 in this case) or even 250Mb (timing multiplied by 1000).

With benchmarked single threaded timing, I'd get the (optimistic) estimate of throughput gain:

single threaded timing 24h would give me >=23h in multithreaded execution

...4h would give me >=3h

...2h would give me >=1h

...1.5h or less would give me >=1h (yeah at less than 2h, parsing would be bottleneck not file reading)

Actually, having benchmark less than 2h I'd also check if parsing could run concurrently because in this case, having more than one thread to parse could increase gain.

Assume 1MB/s IO, can I achive performance throughput with multithreaded mode?

Assuming above, reading 250G file would take about 250.000 seconds. 250 gigabytes is 250 thousands times by 1 megabyte.

250.000 seconds is about three days. Parsing in a separate thread would save you one hour or less of 3 days (~2% I think). It's up to you to decide whether it is worth it. I personally would rather think about something like GFS plus MapReduce to handle stuff like that.


答:
Probably not that it's overly complicated because that makes most people feel bad afterwards.  I assume that when this happens already a lot of code has been written without talking one word about it.  (Why is that so?  Because that person has enough authority so his code doesn't have to be reviewed in reality?)

Otherwise I guess to make code review less formal but more frequent.  And before writing large modules maybe you should quickly discuss what approach to take.

Saying "this is too complicated" gets you nowhere.


答:
An SSL has drawbacks. It slows down your website. Really.

The only reason why people are using SSL certificates is when there is the customers' money involved.

If you are not involving your customers' money, the decision to take an SSL certificate is purely business oriented.

If you're having a backend for your customers, with no money involved on the website, but they need to be sure that they're secure, then sure take a certificate. It's an investment for your customers' trust.


问:
Is there something wrong with how we're doing version control?
I work with a team of programmers as the business analyst.  We just released version 2.0 of our product and are working on the next version to be released in 3 months (it's an internal software product).  Unfortunately version 2.0 has some issues that they have had to fix and we're going to deploy those fixes in a couple weeks.  The problem is that we also don't want to deploy the changes that are still being worked on and are not slated to be released for another 3 months.

The programmers decided that the way to manage this was that only the code for the defects will be checked in, and the code for the new enhancements will be kept on the developer's local machines until they are done.  I will have to get local builds from their machines to test because if they check in the code and we have to push out another patch to fix defects we don't want to include those enhancements just yet.  There is also the problem where the same code file contains both defect fixes and enhancements, so they have to copy the code file locally, then make a change to fix a bug and check that one in, then resume work on the enhancements by taking the local copy they made.

It seems quite convoluted - is there a better way to handle this type of scenario?  We're using Team Foundation Server and Visual Studio 2010.

答:
I'm a developer and we are given different branch code and db for fixes of current version and a different for enhancements and for later consecutive version.

Once our fixes are done they are merged with production and are deployed we get new fresh branch to work again back to enhancements.

Moreover we follow a practice like if I have 10 fixes for my current version

I write as

```<code>//Start Iteration 2, Fix No-1, Branch No-"ABC"
code where I have done changes or fixes or added new code lines
//End Iteration 2, Fix No-1, Branch No-"ABC"
</code>```

Similarly for other fixes, I just do this for each and every line I change or add for fixing. And just compare and commit. Similarly if they were doing parallel on same branch they can use

```<code>//Start Enhancement -1, Branch No-"ABC"
code where I have done changes of fixes or added new code lines
//End Enhancement -1, Branch No-"ABC"
</code>```

Ctrl+Shift+F command and type //Start Iteration 2, Fix No-1, Branch No-"ABC"
to search in entire solution helps a lot to find out exact locations, files where code is changed and take fresh code only that part can be used to commit.

Body:
I'm a developer and we are given different branch code and db for fixes of current version and a different for enhancements and for later consecutive version.

Once our fixes are done they are merged with production and are deployed we get new fresh branch to work again back to enhancements.

Moreover we follow a practice like if I have 10 fixes for my current version

I write as

//Start Iteration 2, Fix No-1, Branch No-"ABC"
code where I have done changes or fixes or added new code lines
//End Iteration 2, Fix No-1, Branch No-"ABC"

Similarly for other fixes, I just do this for each and every line I change or add for fixing. And just compare and commit. Similarly if they were doing parallel on same branch they can use

//Start Enhancement -1, Branch No-"ABC"
code where I have done changes of fixes or added new code lines
//End Enhancement -1, Branch No-"ABC"

Ctrl+Shift+F command and type //Start Iteration 2, Fix No-1, Branch No-"ABC"
to search in entire solution helps a lot to find out exact locations, files where code is changed and take fresh code only that part can be used to commit.


问:
Does "Property" in C# cost much?
I have a class created in some namespace, like SomeNameSpace.SubNameSpace.StaticClassName

Here is a code snippet from other code file where I want to use this class many more times, so I created a property in the code file like this

```<code>//Just to provide an Alias for long name "SomeNameSpace.SubNameSpace.StaticClassName.PropertyName"
public StaticClassName ServerProxyAlias
{
    get
    {
        return SomeNameSpace.SubNameSpace.Instance.PropertyName;
    }
    set
    {
        SomeNameSpace.SubNameSpace.Instance.PropertyName = value;
    }
}
</code>```

Is there any problem in doing like this ?

答:
There's no problem with this code whatsoever.

As long as the actual PropertyName doesn't invoke a long running process then it should be OK.

However, you should really access the property directly. I don't see what the problem is with using the full name.

Title: Does "Property" in C# cost much?


问:
Should I use the Date type in JAX-RS @PathParam?
This is what I'm thinking about doing on a JEE Glassfish server using Jersey.

```<code>@GET
@Path("/{name}/{date}")
public String getMessages(@PathParam("name") String name, @PathParam("date") Date date)
</code>```

I like the idea of being able to tell people consuming this RESTful webservice that "The date here is anything that works with the Date class in Java". That's pretty simple from the standpoint that they can just look at the Date spec, and they'll already have a working model that they can test with.

The problem that I'm worried about is that when I do this, JAX-RS is not very nice when Date() doesn't like what it gets in the constructor. Since Date() throws an error if it can't parse what it's given (like if you pass it the string "today" instead of a real date), the JEE server returns a 404 error.

Is this a good practice? Is there a better way to do this that I'm not thinking of?

答:
I'm using a custom class DateParam:

```<code>@GET
@Path("/{name}/{date}")
public String getMessages(@PathParam("name") String name, @PathParam("date") DateParam date)
  Date date = date.getDate();
</code>```

The class is defined as:

```<code>public class DateParam {
  private final Date date;

  public DateParam(String dateStr) throws WebApplicationException {
    if (isEmpty(dateStr)) {
      this.date = null;
      return;
    }
    final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
      this.date = dateFormat.parse(dateStr);
    } catch (ParseException e) {
      throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
        .entity("Couldn't parse date string: " + e.getMessage())
        .build());
    }
  }

  public Date getDate() {
    return date;
  }
}
</code>```

If the parameter is empty then you would get a null date. You can extend DateParam by a public static final field for undefined date values. This would make testing for undefined date params clearer.

One drawback here is that for each DateParam, a new instance of SimpleDateFormat is created. However, since SimpleDateFormat is not thread-safe, we cannot reuse it easily.

Body:
I'm using a custom class DateParam:

@GET
@Path("/{name}/{date}")
public String getMessages(@PathParam("name") String name, @PathParam("date") DateParam date)
  Date date = date.getDate();

The class is defined as:

public class DateParam {
  private final Date date;

  public DateParam(String dateStr) throws WebApplicationException {
    if (isEmpty(dateStr)) {
      this.date = null;
      return;
    }
    final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
      this.date = dateFormat.parse(dateStr);
    } catch (ParseException e) {
      throw new WebApplicationException(Response.status(Status.BAD_REQUEST)
        .entity("Couldn't parse date string: " + e.getMessage())
        .build());
    }
  }

  public Date getDate() {
    return date;
  }
}

If the parameter is empty then you would get a null date. You can extend DateParam by a public static final field for undefined date values. This would make testing for undefined date params clearer.

One drawback here is that for each DateParam, a new instance of SimpleDateFormat is created. However, since SimpleDateFormat is not thread-safe, we cannot reuse it easily.


问:
Clients with multiple proxy and multithreading callbacks
I created a sessionful web service using WCF, and in particular I used the NetTcpBinding binding. In addition to methods to initiate and terminate a session, other methods allow the client to send to one or more tasks to be performed (the results are returned via callback, so the service is duplex), but they also allow you to know the status of the service.

Assuming you activate the same service on multiple endpoints, and assuming that the client knows these endpoints (for example, it could maintain a List of endpoints), the client should connect with one or more replicas of the same service. The client periodically updates the status of the service, so when it needs to perform a new task (the task is submitted by the user via UI), it selects the service currently less loaded and sends the task to it. Periodically, the client also initiates a maintenance procedure in order to disconnect from one or more overloaded service and in order to connect with new services.

I created a client proxy using the svcutil tool.
I wish each proxy can be used simultaneously by different threads, for example, in addition to the thread that submits the tasks using a proxy, there are also the following two threads which act periodically:

a thread that periodically sends a request to the service in order to obtain the updated state;

a thread that periodically selects a proxy to close and instantiates a new proxy to replace the closed one.

To achieve these objectives, is it sufficient to create an array of proxies and manage their opening and closing in separate threads?
I think I read that the proxy method calls are thread safe, so I would not need to perform a lock before requesting updates to the service. However, when the maintenance procedure (which is activated on its own thread) decides to close a proxy, should I perform a lock?

Finally, each proxy is also associated with an object that implements the callback interface for the service: are the callbacks (invoked on the client) executed on different threads on the client?

I would like to wrap the management of the proxy in one or more classes so that it can then easily manage within a WPF application.

答:
I created a SingleTon class that can be used to Manage this Proxy.</p>

```<code>/// <summary>
/// Singleton Pattern
/// <para>ConnectionHelper provides connection to the Server.</para>
/// </summary>
public sealed class ConnectionHelper
{
    private static readonly ConnectionHelper instance = new ConnectionHelper();
    /// <summary>
    /// Provides a readonly Instance to "ConnectionHelper" class.
    /// </summary>
    public static ConnectionHelper Instance
    {
        get
        {
            return instance;
        }
    }
    /// <summary>
    /// Provides access to IServer members.
    /// </summary>
    public ServerProxy ServerProxyInstance { get; set; }

    /// <summary>
    /// Gets or sets the peer vue communication URL.
    /// </summary>
    /// <value>The peer vue communication URL.</value>
    public string CommunicationURL
    {
        get;
        set;
    }

    .....
    ...
    ..
}
</code>```

Body:
I created a SingleTon class that can be used to Manage this Proxy.

/// <summary>
/// Singleton Pattern
/// <para>ConnectionHelper provides connection to the Server.</para>
/// </summary>
public sealed class ConnectionHelper
{
    private static readonly ConnectionHelper instance = new ConnectionHelper();
    /// <summary>
    /// Provides a readonly Instance to "ConnectionHelper" class.
    /// </summary>
    public static ConnectionHelper Instance
    {
        get
        {
            return instance;
        }
    }
    /// <summary>
    /// Provides access to IServer members.
    /// </summary>
    public ServerProxy ServerProxyInstance { get; set; }

    /// <summary>
    /// Gets or sets the peer vue communication URL.
    /// </summary>
    /// <value>The peer vue communication URL.</value>
    public string CommunicationURL
    {
        get;
        set;
    }

    .....
    ...
    ..
}


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答: I just want to register my vote for Aaron G's suggestion of comefrom -- the first appropriate use I've seen of INTERCAL's COMEFROM statement. The idea is that it's sort of the opposite of GOTO (jumping away from the GOTO statement) in that it makes some place in your code jump to the COMEFROM statement.

ContentLicense: CC BY-SA 4.0

Title: async & await - poll for alternatives


答:
I think it's about consistency as much as readability. Other developers may miss the fact that you implemented a "proxy property" and still refer to SomeNameSpace.SubNameSpace.Instance.PropertyName directly.

Then you end up with code where sometimes ServerProxyAlias is used and sometimes isn't - even in the same method - and it's not obvious they're the same thing, lest one actually looks up how ServerProxyAlias is implemented.

I'm not saying it's a major problem, but you ask about any problems with your approach. Well, that's one that comes to my mind.

Title: Does "Property" in C# cost much?

Body:
I have a class created in some namespace, like SomeNameSpace.SubNameSpace.StaticClassName

Here is a code snippet from other code file where I want to use this class many more times, so I created a property in the code file like this

```<code>//Just to provide an Alias for long name "SomeNameSpace.SubNameSpace.StaticClassName.PropertyName"
public StaticClassName ServerProxyAlias
{
    get
    {
        return SomeNameSpace.SubNameSpace.Instance.PropertyName;
    }
    set
    {
        SomeNameSpace.SubNameSpace.Instance.PropertyName = value;
    }
}
</code>```

Is there any problem in doing like this ?


问:
Using "Context-based" CSS Class Names
This morning I found a note on my desk with some tips from a higher up developer who had been looking over some HTML/CSS I had put together.

One of his suggestions was for me to "stay away from context-based class and ID names like 'left' or 'right.' Never use colors as names. Stick to semantic names based on the content."

Is this valid advice? Why?

答:
Absolutely. You want to start with semantic meaning, then via CSS apply styling to that.

Look at it from a maintenance point of view, long term. Say you have a warning message on your site, and right now you feel that they should be displayed in angry red.

Giving your warning
 the class "red" may look like a good idea now, but what if research showed that a yellow warning label is more effective later? Now you have to go rename both your class name and adjust your styling.

If, however, you had stuck to a semantic class name ("warning"), all you have to do is tweak the styling attached to that semantic label to adjust what it looks like. Now, when you need to add extra margins, a border, a drop-shadow, you don't need to use additional classes either, you are still styling warnings.

Also, by using semantic names, using your HTML code in different contexts is easier. You can now attach JavaScript code to manipulate all div's with the "warning" class, and it'll be clear to anyone else using your code what you are doing with that code. Your JavaScript code is less prone to breakage, as there is far less chance that the CSS class on the warning
 is going to change.

Title: Using "Context-based" CSS Class Names

Body:
Absolutely. You want to start with semantic meaning, then via CSS apply styling to that.

Look at it from a maintenance point of view, long term. Say you have a warning message on your site, and right now you feel that they should be displayed in angry red.

Giving your warning <div> the class "red" may look like a good idea now, but what if research showed that a yellow warning label is more effective later? Now you have to go rename both your class name and adjust your styling.

If, however, you had stuck to a semantic class name ("warning"), all you have to do is tweak the styling attached to that semantic label to adjust what it looks like. Now, when you need to add extra margins, a border, a drop-shadow, you don't need to use additional classes either, you are still styling warnings.

Also, by using semantic names, using your HTML code in different contexts is easier. You can now attach JavaScript code to manipulate all div's with the "warning" class, and it'll be clear to anyone else using your code what you are doing with that code. Your JavaScript code is less prone to breakage, as there is far less chance that the CSS class on the warning <div> is going to change.


答:
Names like left, right as well as color names are very possible to be ambiguous.

In our company we're working on a huge web project. There are thousands of css classes, and it is convenient to name the classes based on the component they work with. This helps you and others know where each css class is used. So when a class content is changed we know where exactly to expect possible changes of the look.

There is another potential problem here. When you name the class left and in a couple of days the design changes slightly so that the element with left must go to right, you can't just edit the content of your class. You'll have to rename it, find all references and rename those too. Or you'll have to create a new class, and the old one will gradually become unnecessary trash.

Title: Using "Context-based" CSS Class Names

Body:
This morning I found a note on my desk with some tips from a higher up developer who had been looking over some HTML/CSS I had put together.

One of his suggestions was for me to "stay away from context-based class and ID names like 'left' or 'right.' Never use colors as names. Stick to semantic names based on the content."

Is this valid advice? Why?


答: As mentioned, it will not make difference. Because once code is compiled into IL it will have almost same hit on performance. Maybe there would be only minor (nano-seconds) difference in compile time.

Title: Does "Property" in C# cost much?


答:
Yes. Definitely valid advice. CSS classes, for the most part, should not be tied directly to what they look like. Tie them, instead, to what they mean.

If you're using .blue to provide emphasis, and your site design changes so that you no longer want your emphasis to be blue, then you have a disconnect between the display of the element, and the class name.

If, instead, you used .emphasize, you could change the color in the CSS, and the HTML attribute would still be meaningful. You get the change without having to touch the HTML (or, in this case, you could style the em tag, and get even better semantics in the HTML).

In addition, it makes your CSS more readable. When you're changing .blue, it's not obvious what elements on your page you're changing. But if you're changing .emphasize or .pull-quote, you can immediately tell.

There are instances when non-semantic class names are unavoidable, but this is mostly when creating generic layout. Things like column or column-left or half or third are necessary in grid-based layouts.

So, my opinion is that layout doesn't need to be semantic, and usually won't be. But content should definitely be semantic. Ask yourself what your content is, and make the class name represent that, so it can be used in a meaningful way.

Title: Using "Context-based" CSS Class Names


问:
Am I shooting myself in the foot if I use Mercurial for Rails development?
I'm a Rails developer and I prefer Mercurial over Git. However, I know that the Rails community is very pro-Git. So my question is it possible that my choice of version control system would turn back some developers?</p>

答:
Honestly, hg and git are fairly similar. For hiring and collaborating, it shouldn't matter too much (though the workflows differ a little bit).

The big sticking point, honestly, would be GitHub. If you plan on open-sourcing your projects, GitHub is the way to go. It's a massive community, and it's frequently searched for libraries and projects by a huge amount of developers. It seems ridiculous that third-party repository hosting would have an effect on which source control systems to use, but if you're an independent dev looking to make a name for yourself, there's no better way to go (right now) than GitHub.

(Apologies for making this sound like a GH advertisement - I am in no way affiliated with GitHub).


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I've always gone for a middle ground:

```<code>if ( i<= 10){
    printf("hello");
    i++;
}
else
    printf("goodbye");
</code>```

I find it the easiest  way to recognize code blocks at a glance while not taking up too much space or making the {} stick out.

Body:
I've always gone for a middle ground:

if ( i<= 10){
    printf("hello");
    i++;
}
else
    printf("goodbye");

I find it the easiest  way to recognize code blocks at a glance while not taking up too much space or making the {} stick out.


答: Referring the question in the title, it costs you as much as invoking a method does. Java's equivalent of properties for example would be getters and setters.</p>

Title: Does "Property" in C# cost much?


问:
What do you say in a code review when the other person built an over complicated solution?
The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist.

In this situation I ask "why was it done this way?"

The answer is the other person felt like doing it that way.

Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user.

The answer is no.

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done".

My view is that it is not done, it's  buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested.

An equivalent scenario is:

Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.

Again the response I get is "well it's already done."

What is an appropriate response to this attitude?

答:
It's unfortunate, but Code Reviews are, a lot of times, more for the future than for the present. Especially in an enterprise/corporate environment, shipped code is always more valuable than unshipped code.

This, of course, depends on when the code review is completed. If it's part of the development process, then you could gain some benefit right now. But if the CR is treated as more of a post-mortem, then you're best off pointing out what could be done better in the future. In your case (as others have said), point out YAGNI and KISS in general, and perhaps some of the specific areas where these principles could be applied.


问:
How do you follow the single responsibility principle in classes responsible for behaviour?
I have many classes in my application responsible for behaviour- views, controllers, models, network- often the state of one class or system depends on another and I'm finding that classes that are primarily responsible for the behaviour for one system inevitably become dependees or dependers of other systems or classes. I've tried passing in interfaces of dependencies from the constructor of the system all the way to the class the depends on it and registering for events on it but this gets extremely complex and crazy and definitely violates OCP and SRP at least.

I'm considering making an event system that all event dispatching and listening classes would be coupled to, providing a layer of indirection for classes that require interaction with classes from other systems however in the worst case behavioural classes could be responsible for the behaviour of a class, handling events, and dispatching events- so that definitely also violates the SRP even though I'm pretty sure it would follow the OCP.

Is there a better solution out there? Am I applying these principles correctly? I'm very hesitant to use an event system as it will require most classes to be extremely tightly coupled with it.

答: If by 'responsibility' we equate 'reason to change' it depends on the granularity of the abstraction.  Taking it to a ridiculous level, one might consider that because every method has its own responsibility there should only ever be one method per class but that's just crazy.  I think that you're on the right lines with your  Interface approach, but instead of injecting the dependencies into constructors you could see if DI/IoC framework or Service Locator pattern works in your scenario.  </p>

OwnerDisplayName: Ford


问:
Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?
I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment.

For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc.

I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month.

This got me thinking maybe the way to go is open source on Linux.

As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS?

My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node.

That's the background - but basically is Linux a good match for:

Hosting a NodeJS/Express site?

Compiling C++ node modules?

Using a NoSQL DB like MongoDB?

And is it a good idea to move to these unfamiliar technologies to save money?

3 MONTH UPDATE

I've been working on this for the past few months now so thought I would give an update in case anyone is interested.

In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product.

After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue.

Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end.

Below is a summary of the tech/frameworks I am currently using:

Standard DB stuff: PostreSQL

Logging & Data Store: MongoDB

ORM: Entity Framework 5

Core libraries: .NET (C#)

Web Framework: ASP.NET MVC3

UI: Razor view engine / BackboneJS

答:
Its not just the cost of that £100/month server, you'll need a properly licensed copy of Windows, Visual Studio, etc etc to work with. These add up considerably if you do it without resorting to software piracy. And once you start to scale and require a lot more servers, and replicating SQLServer, redundancy and all the rest.. well, just remember MS doesn't earn billions of dollars from their Server and Tools division because they give it away. While the cost of your time while you get up to speed will be greater than using what you already know, in the long term, the benefits of the OSS cost will far outweigh your initial investment in time.

In the main, while you may be wary of trying this out using unfamiliar tech, you have to realise that you'll be working with new tech all the time anyway. Using node.js isn't particularly difficult, especially if you already know javascript, so your additional cost of getting a little more familiar with it will be measured in days rather than months. There are plenty of tutorials and examples that will get you up and running with prototype code in no time, and chances are you'll be hitting a rewrite wall once your startup becomes successful no matter what language you write all your code in.

So anyway, Linux is perfectly suited to C/C++ coding, you'll find its one of the most popular systems for Linux, if not the most popular. MongoDB is a fine choice too, apparently the support from 10gen is pretty good. Node.js is good too, though you might end up either writing the majority of your server in node, or using it as a simple pass-through wrapper to your C++ code, depending on how comfortable you get with either of those languages.

And it scales well. I would suggest you keep an eye on Postgresql as it now has a JSON column type which will give you much of the benefits of the NoSQL DBs, but allow you relational DB features too. Postgresql is rock solid, I used it as part of an system for the emergency services so you can trust it for reliability (less downtime than the SQLServer on the same project actually!)

For IDEs on Linux, you want eclipse. Its just like Visual Studio though installing the packages for the CDT (C dev tools) is slightly more complicated.

Lastly, its good to learn new stuff, you might enjoy the Linux experience so much you'll hate going to work :)


答:
I don't know anything that works after the code is written.

Before the code is written, people can discuss alternative ways to do it.
The key is contributing ideas to each other, so hopefully a reasonable one will be chosen.

There's another approach that works with contractors - fixed-price contracts.
The simpler the solution, the more $$ the programmer gets to keep.


答:
This is a tough question to answer.  A specific example of the problem you are experiencing would help to give better guidance.  It sounds like you aren't splitting the responsibilities of your classes correctly so that a given class doesn't have too many dependencies.  As a general rule, I try to avoid a single class having more than 3-4 dependencies.  If you have classes that need a half dozen dependencies or more, I would try to split that class up.

I do agree with you that you should avoid eventing patterns unless you have a really good reason to use them.  Using eventing to get around coupling and SRP issues doesn't seem like a good approach to me.

Title: How do you follow the single responsibility principle in classes responsible for behaviour?

Body:
I have many classes in my application responsible for behaviour- views, controllers, models, network- often the state of one class or system depends on another and I'm finding that classes that are primarily responsible for the behaviour for one system inevitably become dependees or dependers of other systems or classes. I've tried passing in interfaces of dependencies from the constructor of the system all the way to the class the depends on it and registering for events on it but this gets extremely complex and crazy and definitely violates OCP and SRP at least.

I'm considering making an event system that all event dispatching and listening classes would be coupled to, providing a layer of indirection for classes that require interaction with classes from other systems however in the worst case behavioural classes could be responsible for the behaviour of a class, handling events, and dispatching events- so that definitely also violates the SRP even though I'm pretty sure it would follow the OCP.

Is there a better solution out there? Am I applying these principles correctly? I'm very hesitant to use an event system as it will require most classes to be extremely tightly coupled with it.


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答:
Copernic Desktop Search Linkie

This is my weapon of choice on Windows; it searches PDF and text documents, zip files as well as office files. (In total over 150) I also have it set up to only index a specific part of my external HDD.

As far as Linux goes, I actually just rely on the layout of my files and folders - this leaves a lot to be desired!

+1 for Evernote for notes though, I enjoy being able to ammend and read through notes whilst commuting!

Title: How do you manage your knowledge base?


问:
Whats the difference between an interpreted language and one compiled to a VM?
It occurs  to me that there's not a heck of a lot of difference between

$>python module.py

And:

$>javac module.java

$>java module.class

The former compiles to an intermediate language (python bytecode) and executes the program. The latter breaks the steps up, first compiling to the intermediate language (jvm bytecode) and then executing on another line. In fact I can rewrite the python to break out the two steps, as in this SO question.

It seems people make a big deal about the stark difference between compiled and interpreted languages. It seems the lines are entirely blured. Other popular interpreted languages havi similar features. Php "compiles" to its own opcodes which can be cached or stored for later use. Perl also is compiled to something.

So... is there really any difference between these popular interpreted languages and popular compiled languages that compile to VMs? Perhaps in one case the VMs are typically more memory resident whereas with the "interpreted" languages they typically have their runtimes spun up? Yet this seems like it could be easily changed.

Yet there still seems to be something of a difference. If they are more-or-less the same, then why is it that the performance of Java/C# seems to approach C++ while the "interpreted" languages are still an order of magnitude off? If its all truly bytecodes running in a VM, and all really the same, why the big difference in performance?

答:
There are many differences. First of all, think of the difference between a bytecode interpreter and a language interpreter. It's easy to interpret bytecode, because all commands follow a predictable format, but interpreting a language involves parsing and lexing -- operations that can be quite taxing, depending on the language.

C# and Java don't only compile to bytecode. They also use JIT compilation, which allows them to interpert the bytecode a few times for the entire duration of the application, and caching the result -- instead of interpreting it whenever the execution thread stumbles upon it, which would involve lots of redundancy.

As far as I remember, python can compile to bytecode, but it doesn't use JIT, which can drastically increase performance.


问:
How important is an SSL certificate for a website?
I'm bootstrapping my own project, it has a registration/login area (via devise with RoR, properly hashed and salted of course). As I'm using subdomains and I need to access them with iframes (it's justified, really!) I'd need one of those expensive certificates that cover subdomains.

As I'm doing this out of my own time and money, so I'm hesitant to drop a couple of hundreds on a certificate, plus a couple of hours delving into something I haven't tried before. I'm not storing any sensitive information besides the email address and the password. As far as I understand, the only vulnerability happens when a user logs or signs up from an unencrypted network (such as a coffee shop) and someone is listening the network.

Am I being cheap? Is this something I should tackle before releasing into the wild. I probably should mention I have 25,000 users signed up to be notified when I launch, so I'm nervous about it.

答:
Security Concerns

As far as I understand, the only vulnerability happens when a user
  logs or signs up from an unencrypted network (such as a coffee shop)
  and someone is listening the network.

This is not true, data transmitted between the user and your website is never safe.  Just as an example, http://www.pcmag.com/article2/0,2817,2406837,00.asp details the story of a virus that changed people's DNS settings.  No matter how good your current network is protected, any submission on the internet goes through many different servers before it gets to yours. Any one of them can be malicious.

SSL certificates allow you to encrypt your data in a one way encryption that can only be decrypted at your server.  So no matter where the data hops on it's way to your server, no one else can read the data.

In most cases, and this depends on your hosting, installation of a certificate is rather painless. Most providers will install it for you.

SSL Cert Types

As noted in some answers, you can create your own SSL certificates.  An SSL certificate is just a public and private key pairing.  Your server gives out the public key, the client uses it to encrypt the data it's sending, and only the private key on your server can decrypt it. OpenSSL is a good tool for creating your own.

Signed SSL Certificates

Purchasing a certificate from a certificate authority adds another level of security and trust.  Again, it's possible that someone can sit in between the client browser and you web server.  They would simply need to give the client their own public key, decrypt the info with their private key, re-encrypt it with your public key and pass it on to you and neither the user nor you would know.

When a Signed Certificate is received by the user, their browser will connect to the authentication provider (Verisign, etc.) to validate that the public key they received is in fact the one for your website and that there has been no tampering.

So, yes you should have a Signed SSL certificate for you site. It makes you look more professional, gives your users more piece of mind in using your site, and most importantly protects you against data theft.

More info on the Man In The Middle attack that is the core of the issue here.
http://en.wikipedia.org/wiki/Man-in-the-middle_attack


问:
What is the most basic and simple platform for collaborative development (PHP project)?
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.

答:
I recommend your developers to http://try.github.com

But if no version control is possible, you could stick with something fit for the very beginner/junior that is basic (and archaic).

the APP + DB on development server

Everyone on the same messenger all the time while working so they can speak and know who's working

Everyone edits live on the DEV server through plain old FTP

Enforce team rules on updating a changelog with their revisions + making code comments crucial

The setup for your development server's web folder could also be svn checkout (or git) and you can setup the crontab to auto commit revisions every so often automatically or you can just install a backup or maybe rsync the folder to some other backup location for when they overwrite each others files (as it will happen) and you need to give Bob his changes he lost. Eventually after working with the system for a few months they are going to be begging you to give them svn/git access.


答:
You to coder after deleting/rolling back their code: "Oops, your code has gone. Please rewrite it. As you have already written it once you will need less than twenty minutes to provide ONLY the code required by the spec.

"My next review is in 20 minutes.

"Good day."

Do NOT accept any arguments!

Done, IMHO

Chris


问:
When Rob Pike says "Go is about composition", what exactly does he mean?
From Less is Exponentially More

If C++ and Java are about type hierarchies and the taxonomy of types, Go is about composition.

答:
He means that where you'd use something on the order of:

```<code>class A : public B {};
</code>```

in something like Java or C++, in Go you'd use (something equivalent to):

```<code>class A {
    B b;
};
</code>```

Yes, this provides inheritance-like capabilities. Let's expand the example above a little bit:

```<code>struct B {
    int foo() {}
};

struct A {
    B b;
};

A a;

a.foo();  // not allowed in C++ or Java, but allowed in Go.
</code>```

To do this, however, you use a syntax that's not allowed in C++ or Java -- you leave the embedded object without a name of its own, so it's more like:

```<code>struct A {
   B;
};
</code>```

Body:
He means that where you'd use something on the order of:

class A : public B {};

in something like Java or C++, in Go you'd use (something equivalent to):

class A {
    B b;
};

Yes, this provides inheritance-like capabilities. Let's expand the example above a little bit:

struct B {
    int foo() {}
};

struct A {
    B b;
};

A a;

a.foo();  // not allowed in C++ or Java, but allowed in Go.

To do this, however, you use a syntax that's not allowed in C++ or Java -- you leave the embedded object without a name of its own, so it's more like:

struct A {
   B;
};


答:
This question/problem is kind of similar to this one.

In Go, you don't really have OOP.

If you want to "specialize" an object, you do it by embedding, which is a composition, but with some goodies making it partially similar to inheritance. You do it like this :

```<code>type ConnexionMysql struct {
    *sql.DB
}
</code>```

In this sample, ConnexionMysql is a kind of specialization of *sql.DB, and you can call on ConnexionMysql the functions defined on *sql.DB :

```<code>type BaseMysql struct {
    user     string
    password string
    database string
}

func (store *BaseMysql) DB() (ConnexionMysql, error) {
    db, err := sql.Open("mymysql", store.database+"/"+store.user+"/"+store.password)
    return ConnexionMysql{db}, err
}

func (con ConnexionMysql) EtatBraldun(idBraldun uint) (*EtatBraldun, error) {
    row := con.QueryRow("select pv, pvmax, pa, tour, dla, faim from compte where id=?", idBraldun)
    // stuff
    return nil, err
}

// somewhere else:
con, err := ms.bd.DB()
defer con.Close()
// ...
somethings, err = con.EtatBraldun(id)
</code>```

So at first sight you might think that this composition is the tool to make your usual taxonomy.

But

if a function defined on the *sql.DB calls other functions defined on *sql.DB, it won't call the functions redefined on ConnexionMysql even if they exist.

With classical inheritance, you often do something like this :

```<code>func (db *sql.DB) doComplexThing() {
   db.doSimpleThing()
   db.doAnotherSimpleThing()
}

func (db *sql.DB) doSimpleThing() {
   // standard implementation, that we expect to override
}
</code>```

That is, you define doComplexThing on the super class as an organization on calls of the specializations.

But in Go, this wouldn't call the specialized function but the "superclass" function.

So, if you want to have an algorithm needing to call some functions defined on *sql.DB but redefined on ConnexionMySQL (or other specializations), you can't define this algorithm as a function of *sql.DB but must define it elsewhere and this function will only compose the calls to the provided specialization.

You could do it like this using interfaces :

```<code>type interface SimpleThingDoer {
   doSimpleThing()
   doAnotherSimpleThing()
}

func doComplexThing(db SimpleThingDoer) {
   db.doSimpleThing()
   db.doAnotherSimpleThing()
}

func (db *sql.DB) doSimpleThing() {
   // standard implementation, that we expect to override
}

func (db ConnexionMySQL) doSimpleThing() {
   // other implemenation
}
</code>```

This is quite different from the classical overriding of class hierarchies.

Especially, you obviously can't directly have a third level inheriting a function implementation from the second one.

In practice, you'll end using mostly (orthogonal) interfaces and let function compose the calls on a provided implementation instead of having the implementation's "superclass" organizing those calls.

In my experience, this leads to the practical absence of hierarchies deeper than one level.

Too often, in other languages, you have the reflex, when you see that the concept A is a specialization of the concept B, to reify this fact by creating a class B and a class A as a subclass of B. Instead of creating your program around your data, you spend time reproducing the taxonomy of objects in your code, on the principle that this is reality.

In Go you can't define a general algorithm and specialize it. You must define a general algorithm and ensure it's general and works with the provided interface implementations.

Having been horrified by the growing complexity of some hierarchy trees on which the coders were making complex hacks to try to accommodate an algorithm whose logic finally implies all levels, I'd say I'm happy with the simpler Go logic, even if it forces you to think instead of just reifying the concepts of your application model.

Title: When Rob Pike says "Go is about composition", what exactly does he mean?

Body:
From Less is Exponentially More

If C++ and Java are about type hierarchies and the taxonomy of types, Go is about composition.

Body:
This question/problem is kind of similar to this one.

In Go, you don't really have OOP.

If you want to "specialize" an object, you do it by embedding, which is a composition, but with some goodies making it partially similar to inheritance. You do it like this :

type ConnexionMysql struct {
    *sql.DB
}

In this sample, ConnexionMysql is a kind of specialization of *sql.DB, and you can call on ConnexionMysql the functions defined on *sql.DB :

type BaseMysql struct {
    user     string
    password string
    database string
}

func (store *BaseMysql) DB() (ConnexionMysql, error) {
    db, err := sql.Open("mymysql", store.database+"/"+store.user+"/"+store.password)
    return ConnexionMysql{db}, err
}

func (con ConnexionMysql) EtatBraldun(idBraldun uint) (*EtatBraldun, error) {
    row := con.QueryRow("select pv, pvmax, pa, tour, dla, faim from compte where id=?", idBraldun)
    // stuff
    return nil, err
}

// somewhere else:
con, err := ms.bd.DB()
defer con.Close()
// ...
somethings, err = con.EtatBraldun(id)

So at first sight you might think that this composition is the tool to make your usual taxonomy.

But

if a function defined on the *sql.DB calls other functions defined on *sql.DB, it won't call the functions redefined on ConnexionMysql even if they exist.

With classical inheritance, you often do something like this :

func (db *sql.DB) doComplexThing() {
   db.doSimpleThing()
   db.doAnotherSimpleThing()
}

func (db *sql.DB) doSimpleThing() {
   // standard implementation, that we expect to override
}

That is, you define doComplexThing on the super class as an organization on calls of the specializations.

But in Go, this wouldn't call the specialized function but the "superclass" function.

So, if you want to have an algorithm needing to call some functions defined on *sql.DB but redefined on ConnexionMySQL (or other specializations), you can't define this algorithm as a function of *sql.DB but must define it elsewhere and this function will only compose the calls to the provided specialization.

You could do it like this using interfaces :

type interface SimpleThingDoer {
   doSimpleThing()
   doAnotherSimpleThing()
}

func doComplexThing(db SimpleThingDoer) {
   db.doSimpleThing()
   db.doAnotherSimpleThing()
}

func (db *sql.DB) doSimpleThing() {
   // standard implementation, that we expect to override
}

func (db ConnexionMySQL) doSimpleThing() {
   // other implemenation
}

This is quite different from the classical overriding of class hierarchies.

Especially, you obviously can't directly have a third level inheriting a function implementation from the second one.

In practice, you'll end using mostly (orthogonal) interfaces and let function compose the calls on a provided implementation instead of having the implementation's "superclass" organizing those calls.

In my experience, this leads to the practical absence of hierarchies deeper than one level.

Too often, in other languages, you have the reflex, when you see that the concept A is a specialization of the concept B, to reify this fact by creating a class B and a class A as a subclass of B. Instead of creating your program around your data, you spend time reproducing the taxonomy of objects in your code, on the principle that this is reality.

In Go you can't define a general algorithm and specialize it. You must define a general algorithm and ensure it's general and works with the provided interface implementations.

Having been horrified by the growing complexity of some hierarchy trees on which the coders were making complex hacks to try to accommodate an algorithm whose logic finally implies all levels, I'd say I'm happy with the simpler Go logic, even if it forces you to think instead of just reifying the concepts of your application model.


答:
What does overly complicated mean? You make an ambiguous statement then you will get an ambiguous/unsatisfying answer in response. What is overly complicated to one person is perfect to another.

The purpose of a review is to point out specific problems and errors, not to say you don't like it, which is what the statement "overly-complex" implies.

If you see a problem (overly-complicated) then say something more concrete like:

Wouldn't changing part X to Y simplify the code or make it easier to understand?

I don't understand what you are doing here in part X, I think what you were trying to do is this. Present a cleaner way of doing it.

How did you test this? Did you test this? If it is overly-complicated this will usually lead to blank stares. Asking for tests will then frequently get the person to self-simplify their code when they couldn't figure out how to test the original code.

There seems to be an error here, changing the code to this would fix the problem.

Anybody can point out problems, especially ambiguous ones. There's a much smaller subset that can present solutions. Your review comments should be as specific as can be. Saying something is overly complex doesn't mean much, it may even cause others to think YOU are incompetent for not being able to understand the code. Keep in mind that most developers don't have a clue of the difference between a good or bad design.