答:
Con for generic services:

Generic services are nightmares to maintain.  You can't easily decipher what's going on. And they are hard to test since there are generic.  If the contract is defined, I can use a tool like SOAP UI to create test messages pretty easily.  If generic, I have to craft the XML by hand (I could still use SOAP UI to send it).   Yuck.  Strike 1 for maintainability and 2 for testability.

Everything with generic services comes in as an XML string.  Everything that is not a string needs to be cast or converted to the correct type.  Because of this they will be slower and consume more resources.  Extra XML parsing and dynamically invoking methods from strings has more overhead.  Strike 3 for needless XML parsing, cast and conversion, and service performance.

I did a somewhat generic data model and service once where part (not all) of the message was meta data and it was much tougher for people to understand how the data went in and came out.  It was flexible but in the end probably a more explicit contract could have been used since there haven't been too many additions/changes that utilized it's flexibility since the service inception.

The silver bullet of never having to change a system again because it is generic is never realized.  It's a dream that exists in the astro-architecture head.

Services are better served with explicit contracts.  You send me X and I'll give you back Y as defined in the contract.  I can publish my contract to consumers so they can code against it and even mock it prior to service release.

Change happens, so version your services contracts.  No big deal to run a few different versions of the service on your web server by having different URLs.

One generic service to rule them all is best served in the fires of Mount Doom.

Title: Service Design approach - one generic operation, and its implications

Body:
The hot topic in our organization is Service Design Approach.

First Approach - The team wants to design services which essentially have one operation, can take any XML and return response XML message. The operation and the parameters are in the request XML message.  Once the message is received the service determines the action/method that is requested. Reasons cited are ease of deployment and flexibility of introducing future operations.

Second Approach - The second group is adamant about well defined service contracts and specific messages.   Reasons cited are better performance, message validation and versioning.  This is my preferred approach as well.

What are the Pros and Cons?  Can there be challenges introducing an ESB later in the architecture if we have chosen the first approach?


问:
How to remove the boundary effects arising due to zero padding in scipy/numpy fft?
I have made a python code to smoothen a given signal using the Weierstrass transform, which is basically the convolution of a normalised gaussian with a signal.

The code is as follows:

```<code>#Importing relevant libraries
from __future__ import division
from scipy.signal import fftconvolve
import numpy as np

def smooth_func(sig, x, t= 0.002):
    N = len(x)
    x1 = x[-1]
    x0 = x[0]

# defining a new array y which is symmetric around zero, to make the gaussian symmetric.
    y = np.linspace(-(x1-x0)/2, (x1-x0)/2, N)
    #gaussian centered around zero.
    gaus = np.exp(-y**(2)/t)

#using fftconvolve to speed up the convolution; gaus.sum() is the normalization constant.
    return fftconvolve(sig, gaus/gaus.sum(), mode='same')
</code>```

If I run this code for say a step function, it smoothens the corner, but at the boundary it interprets another corner and smoothens that too, as a result giving unnecessary behaviour at the boundary. I explain this with a figure shown in this image

This problem does not arise if we directly integrate to find convolution. Hence the problem is not in Weierstrass transform, and hence the problem is in the fftconvolve function of scipy.

To understand why this problem arises we first need to understand the working of fftconvolve in scipy.

The fftconvolve function basically uses the convolution theorem to speed up the computation.

In short it says:

```<code>convolution(int1,int2)=ifft(fft(int1)*fft(int2))
</code>```

If we directly apply this theorem we dont get the desired result. To get the desired result we need to take the fft on a array double the size of max(int1,int2). But this leads to the undesired boundary effects. This is because in the fft code, if size(int) is greater than the size(over which to take fft) it zero pads the input and then takes the fft. This zero padding is exactly what is responsible for the undesired boundary effects.

Can you suggest a way to remove this boundary effects?

I have tried to remove it by a simple trick. After smoothening the function I am compairing the value of the smoothened signal with the original signal near the boundaries and if they dont match I replace the value of the smoothened func with the input signal at that point.

It is as follows:

```<code>i = 0
eps=1e-3
while abs(smooth[i]-sig[i])> eps: #compairing the signals on the left boundary
    smooth[i] = sig[i]
    i = i + 1
j = -1

while abs(smooth[j]-sig[j])> eps: # compairing on the right boundary.
    smooth[j] = sig[j]
    j = j - 1
</code>```

There is a problem with this method, because of using an epsilon there are small jumps in the smoothened function.

Can there be any changes made in the above method to solve this boundary problem?

答:
Use gaussian_filter instead of fftconvolve.

Compare the behavior of fftconvolve (with mode='same') to gaussian_filter (with mode='constant'):

```<code>import numpy as np
from scipy.signal import fftconvolve
from scipy.ndimage import gaussian_filter

x = np.linspace(-3, 3, 51)
y = np.sin(x)

blurring_kernel = np.zeros_like(x)
blurring_kernel[25] = 1
blurring_kernel = gaussian_filter(blurring_kernel, sigma=3)

a = fftconvolve(y, blurring_kernel, mode='same')
b = gaussian_filter(y, sigma=3, mode='constant')
print max(abs((a - b))) # a and b are identical
"""
You have to assume *something* outside the boundary.
This is probably what you want:
"""
c = gaussian_filter(y, sigma=3, mode='reflect')
</code>```

You have to assume something outside the boundary of your signal. fftconvolve assumes zeros. gaussian_filter lets you choose from several different assumptions, and I find one of these is usually closer to my needs than assuming zeros.

For a quick fix, you could use gaussian_filter, or else pad your signal with something nonzero, to get the same effect at the boundary, perhaps using pad.

ContentLicense: CC BY-SA 3.0

Body:
Use gaussian_filter instead of fftconvolve.

Compare the behavior of fftconvolve (with mode='same') to gaussian_filter (with mode='constant'):

import numpy as np
from scipy.signal import fftconvolve
from scipy.ndimage import gaussian_filter

x = np.linspace(-3, 3, 51)
y = np.sin(x)

blurring_kernel = np.zeros_like(x)
blurring_kernel[25] = 1
blurring_kernel = gaussian_filter(blurring_kernel, sigma=3)

a = fftconvolve(y, blurring_kernel, mode='same')
b = gaussian_filter(y, sigma=3, mode='constant')
print max(abs((a - b))) # a and b are identical
"""
You have to assume *something* outside the boundary.
This is probably what you want:
"""
c = gaussian_filter(y, sigma=3, mode='reflect')

You have to assume something outside the boundary of your signal. fftconvolve assumes zeros. gaussian_filter lets you choose from several different assumptions, and I find one of these is usually closer to my needs than assuming zeros.

For a quick fix, you could use gaussian_filter, or else pad your signal with something nonzero, to get the same effect at the boundary, perhaps using pad.


问:
How do you handle supporting Chrome versions?
I'm working on a site for my company which, up until a certain point, was an Internet Explorer-only site for various reasons, mainly that when the site was originally conceived IE had a 90%+ market share so the work to get it working in other browsers just didn't make sense.

Now that we live in a more diverse browser economy we're doing the work to get the site working everywhere, and as luck would have it a decent chunk of it just happens to already work.

However, one issue we're struggling with is the issue of what to support and what not to support. For starters, non-IE browsers release much more frequently than IE did, and you don't know which versions are still in the wild. There's been basically three versions of IE released in the last decade, and IE6 is still supported until 2014. But there's an update for Firefox every other day, Apple updates Safari more or less annually. And then there's Chrome.

Chrome has gone from 0.2 to 9.0 in a little over two years. 7.0.517 was released a month and a half after 6.0.472. There's three different versions out right now, a stable, a beta, and a dev. And the dev version of 9.0.587 was actually released before the latest beta version of 8.0.552.

With IE we've had the situation arise where we have to support an old version because the IT department of the company in question does not allow the employees to upgrade. With non-IE browsers I'm thinking we'll adopt the line of "update to the latest or we can't help you" but I'm not sure how effective that is.

Also, my company does some amount of artificial limitations. For example we have a product aimed at companies so we don't support "Home" versions of Windows (i.e., XP Home, 7 Home Premium) even though there's no technical reason we couldn't.

When my company starts asking "what version or versions of Chrome do we support", how should I answer?

答:
Chrome, Safari, and others use WebKit as the core (see http://en.wikipedia.org/wiki/WebKit#Usage ).  What this means is that making things look good in Chrome will make it render the same in all those other browsers.  Firefox uses another rendering engine.  Bottom line is that they are all standards compliant browsers.  Even IE has been stepping up to the plate with IE 8 and now IE 9.  Standards compliance means it's a whole lot easier to make things look the same and behave the same across all the browsers.

The good news is that a bunch of people have done a lot of work to build cross-browser capable CSS and Javascript.  If you use these frameworks, you stand a good chance of not having to worry too much about cross-browser issues.

The shortlist of CSS frameworks:

Blueprint CSS: http://www.blueprintcss.org/

Elastic CSS: http://elasticss.com/

Yahoo UI (YUI): http://developer.yahoo.com/yui/

The shortlist of Javascript frameworks:

Prototype: http://prototypejs.org

Script.aculo.us: http://script.aculo.us (uses prototype)

JQuery: http://jquery.com

Yahoo UI (YUI): http://developer.yahoo.com/yui/

Newer versions of browsers make more of the current HTML/Javascript/CSS standards work.  As long as you stay away from the cutting edge stuff, you will have no problems.  HTML 4 and CSS 2 have the most support.  If you use something from the newer standards (like HTML 5, currently in development or CSS 3), then provide fallbacks to the known standards.  In short if you put the fallback in your CSS first, and the enhanced look second, the browsers that support that CSS setting will use it and the ones that don't will use the fallback.

Short Answer

Say you support web standards X: HTML 4, CSS 2, etc.  instead of saying you support specific versions of a browser.

ContentLicense: CC BY-SA 2.5


问:
Can only integers be stored as register variables?
I am confused about this: what type of data can we store in register variables?
I guess logically we can store any kind of data as register variables because they are variables, but really I am confused.

I have tried to search on internet and in my book. I couldn't find the answer. By book I am referring to ANSI C's programming book.

答:
Let's look at what the ISO C standard actually says (I'll refer to the 2011 edition, a draft of which is available as N1570.

6.7.1p6:

A declaration of an identifier for an object with storage-class
  specifier register suggests that access to the object be as fast as
  possible. The extent to which such suggestions are effective is
  implementation-defined.

Note that it says nothing about storing the object in a CPU register.

Elsewhere, the standard says that an external declaration may not use the register keyword; it can only be used for variables declared inside the body of a function.

Attempting to take the address of a register-qualified object is not allowed. (That means that declaring an array with register, though it's legal, is not particularly useful; you have to take its address to be able to do indexing).

Apart from that, a compiler is free to ignore the register keyword, treating it as equivalent to auto. You can apply the register keyword to any variable you like (as long as it's defined locally), regardless of its type or size -- but the only thing the compiler is obligated to do is to complain if you try to take its address.

A compiler is also free to store anything it likes in CPU registers, whether you use the register keyword or not, as long as the behavior is the same as if the variable were stored in memory. This includes storing a variable in a register for its entire lifetime (if the code happens not to try to compute its address), or retrieving its value from a register where the compiler knows it happens to be stored rather than re-loading from memory.

The common wisdom these days is that compilers are better than humans at deciding which variables should be placed in registers for greater speed, so the register keyword is of limited usefulness. In the Old Days, when systems were so small and slow that compilers couldn't afford to do that kind of analysis and dinosaurs roamed the Earth, register could be very useful. With modern compilers, not so much.


问:
Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?
In some code I'm writing right now, I have something like this:

```<code>if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}
</code>```

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go  under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

答: I don't have a fixed rule, but generally I follow this - first, consider where there's a missed design pattern that will factor this out. If not, I write it so that the condition in the if is the most clearly understood. That is, avoiding double negatives and the like.</p>


答:
Order by their likelihood of being executed. The most common, most likely, etc. condition(s) should go first.

The "difficulty of dealing with them" should be dealt with by code structure, abstraction, etc. in the example the else block could be refactored to single method call. You want your if clauses to be at the same abstract level.

```<code>if ( ! LotteryWinner ) {
    GoToWorkMonday();
} else {
    PlanYearLongVacation();
}
</code>```

Title: Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?

Body:
In some code I'm writing right now, I have something like this:

```<code>if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}
</code>```

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go  under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

Body:
Order by their likelihood of being executed. The most common, most likely, etc. condition(s) should go first.

The "difficulty of dealing with them" should be dealt with by code structure, abstraction, etc. in the example the else block could be refactored to single method call. You want your if clauses to be at the same abstract level.

if ( ! LotteryWinner ) {
    GoToWorkMonday();
} else {
    PlanYearLongVacation();
}


答: For me it's more about the conditions than the complexity of the code they execute. You need to order the conditions so as to trap unusual conditions first, then the more common after. Also, if the else code is really long and complicated, I'd probably make a sub for that, to keep the conditional part obvious for the reader.</p>


问:
Is it possible to tag only a portion of a git push?
I'm very new to git, but last week I installed it, set up bitbucket, and pushed my current project to my first bitbucket repo. All went well and I'm pleased with git as a simple, powerful, yet free way to back up my source code offsite, as well as keep track of my changes.

My next step is to keep track of actual version numbers. I'm developing in Visual Studio, where the version numbers live in the project's assembly information. I've read that version numbers are usually tracked in git with tags, so I went to tag my commit with the current version number I'm on. At this point I realized that the project that I linked to my bitbucket repo contains two projects, an application and a set of web services. At this moment they share the same version number, but most likely in the future they will have differing version numbers.

Right now each of these projects is in their own folder in the repo's root directory. Is there a way for me to mark one of these directories with one tag, and the other directory with another? Or should I step back and create two separate repos, one for the application, and the other for the web services?

答:
A tag always points to a specific commit, so no. A commit is a given state of the repo in time. You can either use two different sets of tags (e.g. web-v-2.1 and services-v-5.2) or break up the projects into their own repositories.

At the end of the day, I don't think you really care if a tag contains a specific set for the other folder. I'd just pick tags that represent what I was interested in even if it applies to the entire repo when describing just part of it.


问:
Should I Aggregate Web API Errors?

The Situation

We are writing a REST API that performs validation up-front.
The code is written such that it tries to find as many errors as possible.
However, each error might correspond to a different HTTP status code.
Additionally, the client (the HTML) doesn't have a convenient way to parse/display the errors.

The Question

Is it better to just throw as soon as the first error occurs?
Or should we do our best to aggregate the errors somehow?
By the way, there is no requirement to try to handle as many as possible at once.

I am not looking for an opinion.
I was curious if there was a standard practice in REST.

Why It Matters

The current code is really complex.
Some validation can only be run if other pieces are valid.
So there is this explicit dependency between tests.
It is complex enough that it warrants using a 3rd-party library.
But I would rather just eliminate the cause of the complexity if I am going to spend time on it.

答:
Aggregating errors can become horribly complex. Not only do you have the complexity of identifying what has gone wrong, you need to identify how and branch off a new behaviour to inform the user of the specific error. In addition, you also need some behaviour to detect that an error has occured, and that it must begin aggregating and feeding back errors instead of resuming normal procedures.

One solution would be to aggregate errors found, then simply inform users of what is considered valid input data. In the example of username and password, if both were incorrect, most websites would aggregate the two failing fields, then simply display a static output message for both. E.g:

Username must begin with blah blah, be blah characters long and not contains special characters.

Password must be longer than blah characters long and contain one blah, one blah and one blah.

Second solution would be to simply feed back the first error you get, and let the user retry submission of data, to find more errors.

Advantages of solution one: User will probably get enhanced experienced due to the aggregate of feedback, and is also probably smart enough to be capable of making the input valid from the messages received.

Advantages of solution two: Feedback will be quicker, but will only return one error. User will need to resubmit to gather more feedback which may in turn become frustrating. However, it will also be easier to implement, and in the same vein, the user should get there eventually.

Title: Should I Aggregate Web API Errors?


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: StackOverflow, programmers.stackexchange.com, etc. :)</p>

Title: What can slow a developer down?


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答: If you believe something, say it and mean it, but once proven wrong or outranked, accept it and learn from it. Teamwork isn't about agreeing all the time, but having a way to get to the best possible solutions in the given situation and time-frame.</p>


问:
How to deal with hard configurations at the component level?
I distinguish three organisation levels while programming: the library level, the component level and the application level.  A library defines functions to solve a range of related problems or preform related operations in tools and no policies manner. An application lets several libraries interact and defines policies for diagnostic, error handling, internationalisation,… A component sits between the library and the application, it handles low-level errors and produce diagnostics, it might old global state and is aware of other components.

Now I have a library implemented as a functor parametrised by a module holding a constant n and values associated to different values of n have incompatible types—which is the purpose of implementing the library as a functor.  I call such a configuration a hard configuration, because it must somehow be hard-coded in the program.

Now I am facing the following problem: In this setting, I want to allow the user of the program to choose the value of n for the duration of the program.  Since the library is a functor, one feels forced to write the component interfacing the library to the program as a functor.  But I want the choosed value of n to be a property of the component, not of the application, and I want component to be regular modules (no functor allowed).

How can I wrap a parametric library (implemented as a functor) in a non-parametric component, so that parameters can be chosen when the application starts?  I insist on being able to express the application logic at the highest level in terms of non parametric modules, and want to avoid russian-dolls-alike parametrised modules at this level.

答:
This sounds exactly like the intended use-case of first-class modules:

A typical use of first-class modules is to select at run-time among several implementations of a signature.

http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec230

Another thought would be to implement component config parameters as mutable cells, something like this:

```<code>module Component :
sig
  val init : ?foo:int -> ?bar:float -> ?baz:string -> unit -> unit
  val foo : unit -> int
  val bar : unit -> float
  val baz : unit -> string
end = struct
  module Default =
  struct
    let foo = 0
    let bar = 0.
    let baz = ""
  end
  let store_foo = ref Default.foo
  let store_bar = ref Default.bar
  let store_baz = ref Default.baz
  let init ?(foo=Default.foo) ?(bar=Default.bar) ?(baz=Default.baz) () =
    ( store_foo := foo
    ; store_bar := bar
    ; store_baz := baz
    )
  let foo () = !store_foo
  let bar () = !store_bar
  let baz () = !store_baz
end
</code>```

Body:
This sounds exactly like the intended use-case of first-class modules:

A typical use of first-class modules is to select at run-time among several implementations of a signature.

http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec230

Another thought would be to implement component config parameters as mutable cells, something like this:

module Component :
sig
  val init : ?foo:int -> ?bar:float -> ?baz:string -> unit -> unit
  val foo : unit -> int
  val bar : unit -> float
  val baz : unit -> string
end = struct
  module Default =
  struct
    let foo = 0
    let bar = 0.
    let baz = ""
  end
  let store_foo = ref Default.foo
  let store_bar = ref Default.bar
  let store_baz = ref Default.baz
  let init ?(foo=Default.foo) ?(bar=Default.bar) ?(baz=Default.baz) () =
    ( store_foo := foo
    ; store_bar := bar
    ; store_baz := baz
    )
  let foo () = !store_foo
  let bar () = !store_bar
  let baz () = !store_baz
end


问:
Which is better API: table.add_row() or table.rows.add()?
I'm writing a library to create and manipulate Word .docx files in Python. In general, I take a lot of influence from the Microsoft VBA/C# API for Word in designing the API, figuring they've given it a lot more thought than I'll ever be able to. Several times I've found the wisdom in designing it the way they did only after getting much further down the road.

A table has the properties .rows and .columns, each of which is a sequence of the Row and Column instances in the table, respectively. In the MS API, the methods for adding a new one are Table.rows.add() and Table.columns.add().

I'm inclined to believe this is more complicated than necessary, making my API harder for beginners to learn without really providing any benefit.  I'm thinking Table.add_row() and Table.add_column() would better suit. As it happens, it also simplifies the code somewhat; that's not a motivator, just an observation that I wonder might be trying to tell me something.

Is there an argument for preferring the former?

答:
It's generally easier to manage a hierarchical system of things than a flat structure when there's more than a few of them. Your two methods don't reveal this, there's only two. But you also need delete_column, move_column, sort_column, column_width, column_border and so on, plus the same for rows...

I suspect you'll find that there's a big tree of properties and methods attached to the table. And just the properties will be a fairly long list. It'll probably have categories of properties - appearance, structure, behaviour and more. Each property will have methods and properties of its own. Thousands of them, in all likelihood.

The combination of nodes like those, plus the links between them (the dots, in this notation - so the node "table" links to "column") gives you a big, complex graph. Note that the graph might have loops and other things, it's not just a tree. Which means it might not be even possible to flatten it the way you are thinking of.

For example, the table, the column, the cell all have a font property. And fonts have a bold property. So, how many "bold" properties will your flattened list have?

This is one of the things object oriented design started out trying to solve, BTW - "things" in the code that have both attributes (bold) and behaviour (add_row). Relationships in this case are just attributes "has a" (references and pointers) or "is a" (inheritance).


问:
Development console commands registration
I have a DevelopmentConsole class. I am making functionality to register console commands for the subsystems. I don't want the console to know about them but also I don't want them to contain a debug code (like "Console.RegisterCommand...").

I think I should make an additional class hiearachy. For an example I have Player class.

```<code>IConsoleBuilder {
    RegisterCommand(string command, Func<string[], string> action);
}

PlayerConsoleBuilderClient : ConsoleBuilderClient {
    readonly Player _player =  ?inject?

    public override void Visit(IConsoleBuilder builder) {
        // builder.RegisterCommand("GetName", args => _player.Name) ;
    }
}
</code>```

Here I need to use Reflection to find all ConsoleBuilderClient subclasses. It's not a very good idea, is it?

Can you suggest how to do it in a better way?

答:
There are only 2 options. You either explicitly define each client class in some kind of collection. Probably in some kind of topmost project. Or you use reflection to look for all subclasses of ConsoleBuilderClient in all loaded/available assemblies.

It is up to you to pick which one you prefer.


问:
Why learn git when there are GUI apps for GitHub?
Given that GitHub provides GUI apps for both Mac and Windows, what are the benefits of learning to use git from the command line?

Currently I'm using their mac app to update my repositories, and so far it seems to cover my needs. What might I be missing out on?

答:
I don't know about GitHub for Mac, but the Windows app only perform the most common tasks -- add, commit, push, pull, etc.  More complex tasks like git merge --no-ff have to be performed from command line.

Also, there are cases with git when GUI is not available, e.g. when SSHing into remote servers.

But otherwise, if GUI gives you everything you need then learning command line may be a waste of time.  My work uses TortoiseSVN in Windows-only environment, and I have not had to touch SVN command line even once.


问:
Coworker that detrimentally picks on every minutia
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?

答:
Review: "Works well when cornered like a rat in a trap under constant supervision"

(Someone please let me know a citation for the above)

Micro-managing an entirely unmotivated employee is not going to work. The more you spoon-feed them the more dependent on you they become. You need to find a way to motivate Chris so that s/he wants to work. So, here are some tactics (trimmed from this article) some of which I've highlighted as being particularly relevant here.

Consequences – Never use threats. They’ll turn people against you. But making people aware of the negative consequences of not getting results (for everyone involved) can have a big impact. This one is also big for self motivation. If you don’t get your act together, will you ever get what you want?

Pleasure – This is the old carrot on a stick technique. Providing pleasurable rewards creates eager and productive people.

Kindness – Get people on your side and they’ll want to help you. Piss them off and they’ll do everything they can to screw you over.

Deadlines – Many people are most productive right before a big deadline. They also have a hard time focusing until that deadline is looming overhead. Use this to your advantage by setting up a series of mini-deadlines building up to an end result.

Team Spirit – Create an environment of camaraderie. People work more effectively when they feel like part of team — they don’t want to let others down.

Recognize achievement – Make a point to recognize achievements one-on-one and also in group settings. People like to see that their work isn’t being ignored.

Personal stake – Think about the personal stake of others. What do they need? By understanding this you’ll be able to keep people happy and productive.

Trust and Respect – Give people the trust and respect they deserve and they’ll respond to requests much more favorably.

Create challenges – People are happy when they’re progressing towards a goal. Give them the opportunity to face new and difficult problems and they’ll be more enthusiastic.

Let people be creative – Don’t expect everyone to do things your way. Allowing people to be creative creates a more optimistic environment and can lead to awesome new ideas.

Constructive criticism – Often people don’t realize what they’re doing wrong. Let them know. Most people want to improve and will make an effort once they know how to do it.

Demand improvement – Don’t let people stagnate. Each time someone advances raise the bar a little higher (especially for yourself).

Make it fun – Work is most enjoyable when it doesn’t feel like work at all. Let people have fun and the positive environment will lead to better results.

Create opportunities – Give people the opportunity to advance. Let them know that hard work will pay off.

Make it stimulating – Mix it up. Don’t ask people to do the same boring tasks all the time. A stimulating environment creates enthusiasm and the opportunity for “big picture” thinking.

All in all, you could look at the Chris situation as being a personal challenge. You need to think creatively in order to find the solution (asking on this forum counts as creative BTW) so perhaps apply some of these motivational techniques to yourself in light of the resistance you can expect from Chris.


问:
API design with references to root object
[Normally I post on StackOverflow but as this is more a design/theory question rather than a code question I'll give it a shot here]

Most of my applications currently use a core object model that I originally wrote 6 years ago and which has just grown as needed - as with most of my stuff, it was coded as is, without thinking up a design first. Part of it is too inflexible, part is poorly designed and yet more is clunky. So I decided to start again from scratch rather than trying to retrofit a new API on top of the existing one. And I also decided to actually map out the full API first upfront, then write the code for it.

So far that approach is paying off I suppose and I have a nice little model brewing. However, I have one quandary in the new design. If you consider the automation models offered by things like Microsoft Word, most primary objects have a property named Application which points back to a core object. My existing object model follows pretty much the same principle and I am using that in the new one too.

The current API however has a mix of approaches. Some objects store a reference to that root object. Others don't, and the property simply looks at a singleton "service" object, which at it's heart has a ServiceContainer to look up registered objects. Yes, a service locator. Some get it passed in through a constructor, others look it up then store a reference. I normally like consistency, but this is a mess.

My new design isn't changing this approach - objects still will have a property back the the root object with the idea being all the objects behave the same and I don't have to (manually) go hunting for an application when writing code for a given implementation.

With that background information out of the way, here's my question. Should each object hold a reference to the root object, or should it not store a direct reference, but look it up somehow, ie from a singleton or a service locator.

With the former approach, I'm going to use more memory - 4 bytes extra per object per object as I currently compiled everything as 32bit. While that doesn't sound a lot and I'm sure I'm not going to be creating many thousands of objects I sort of want the base API to be as efficient as possible as no doubt the apps I stick on top of it won't be! This approach also means I'm going to have to pass that object reference around in every single constructor, not much of a problem for real code but makes writing tests a bit more complicated.

The latter approach means I save memory, but then I continue to use the bad practice of a service locator, and I supposed there's a at least the hint of a performance issue as having to lookup a reference isn't quite going to be as quick as returning a direct one.

Or, is there another approach that large object models use that I haven't considered above? As mentioned I normally just dive in, make something that works then leave it alone until it breaks or I need it to do something else.

I'm guessing the answer is going to be "just store the reference and stop complaining" but better to get a feel for other peoples opinions!

答:
Core objects have a strong tendency to become "God objects" over time, so the first thing I would ask here is "do I really need that thing?". The object models of Word or Excel reflect the fashion in object modeling ~15 year ago, when those models where created. But look for example at the .NET framework and, for example, WinForms - there is no Application object, only a static class "Application" with a handful of methods, and in real programs you very seldom need to access that class.

But if you are convinced you really need some kind of "Application" or "core" object, I would tell you "just use the service locator consistently and stop complaining about performance issues you don't really have".  The service locator is sometimes seen as an anti pattern because it could introduce hidden global dependencies, but if you introduce your global dependency to a "core object" through a service locator or by a reference in every of your main objects does not really make a difference, I would consider that as "equally bad".

I suggest you read the "Disadvantages" part of the Wikipedia article about Service Locator, and think a while which of those points really apply in your situation, when accessing your "core object" through such a mechanism, and which of those points are caused just by the fact you have such a "core object".


答:
Should each object hold a reference to the root object, or should it not store a direct reference, but look it up somehow, ie from a singleton or a service locator.

In an ideal world, none of your children should have any knowledge of the thing that contains them. Specifically by doing so, you've eliminated any hope of reuse in a different application. Worse yet, these root objects often let you get at their children, providing a nice gateway for your children to not just depend on this core object, but to their kin.

Good design is predicated on the concept that things only need to know about what they need to do their single responsibility. Do your components need the entirety of this root God object to function? I sincerely doubt it.

Instead, have these components declare what they need, and let the code that builds/assembles/uses them supply the thing that satisfies that need. This way, you get all of the benefits of proper decoupling - testability since tests can pass in different implementations, maintainability since the component only worries about itself and changes to other stuff does not impact it, and flexibility since different consumers can tweak the object specifically to their needs.

Title: API design with references to root object

Body:
[Normally I post on StackOverflow but as this is more a design/theory question rather than a code question I'll give it a shot here]

Most of my applications currently use a core object model that I originally wrote 6 years ago and which has just grown as needed - as with most of my stuff, it was coded as is, without thinking up a design first. Part of it is too inflexible, part is poorly designed and yet more is clunky. So I decided to start again from scratch rather than trying to retrofit a new API on top of the existing one. And I also decided to actually map out the full API first upfront, then write the code for it.

So far that approach is paying off I suppose and I have a nice little model brewing. However, I have one quandary in the new design. If you consider the automation models offered by things like Microsoft Word, most primary objects have a property named Application which points back to a core object. My existing object model follows pretty much the same principle and I am using that in the new one too.

The current API however has a mix of approaches. Some objects store a reference to that root object. Others don't, and the property simply looks at a singleton "service" object, which at it's heart has a ServiceContainer to look up registered objects. Yes, a service locator. Some get it passed in through a constructor, others look it up then store a reference. I normally like consistency, but this is a mess.

My new design isn't changing this approach - objects still will have a property back the the root object with the idea being all the objects behave the same and I don't have to (manually) go hunting for an application when writing code for a given implementation.

With that background information out of the way, here's my question. Should each object hold a reference to the root object, or should it not store a direct reference, but look it up somehow, ie from a singleton or a service locator.

With the former approach, I'm going to use more memory - 4 bytes extra per object per object as I currently compiled everything as 32bit. While that doesn't sound a lot and I'm sure I'm not going to be creating many thousands of objects I sort of want the base API to be as efficient as possible as no doubt the apps I stick on top of it won't be! This approach also means I'm going to have to pass that object reference around in every single constructor, not much of a problem for real code but makes writing tests a bit more complicated.

The latter approach means I save memory, but then I continue to use the bad practice of a service locator, and I supposed there's a at least the hint of a performance issue as having to lookup a reference isn't quite going to be as quick as returning a direct one.

Or, is there another approach that large object models use that I haven't considered above? As mentioned I normally just dive in, make something that works then leave it alone until it breaks or I need it to do something else.

I'm guessing the answer is going to be "just store the reference and stop complaining" but better to get a feel for other peoples opinions!


答:
If all you're doing is mapping the Word API commands, you may not be giving any actual value over just spooling up an instance of winword.exe and utilizing the API over COM.  So, you should consider what it is that you're trying to achieve.

If you're trying to replace the COM calls with a native implementation, you should hew as close to the underlying API as practical.  It would be valuable to be able to invoke a same-process library to generate the appropriate WordML as either an XML or a ZIP'd archive (renamed to DOCX, of course), but if you do so there's no value in deviating from the extant API.

If instead you're trying to simplify the process of creating or populating a Word Document in Python, your API should be focused on the use case you present rather than replicating what Word provides.  There are lots of concepts in Word's model that only make sense due to word's peculiarities, and aren't necessary if you're going to be filling out a "form" based on fields, or adding multiple paragraphs, or adding rows from some data query.  In general, you should implement your own methods, and only copy the Word interface when necessary.

Personally, I'm a big fan of higher-level task methods, like your proposed Table.add_row() method, that provide additional functionality.  Being to able to call add_row and pass it the values for that row would be useful, especially if you could abstract it to an add_rows method to make a table from a two-dimensional array or similar construct.

Title: Which is better API: table.add_row() or table.rows.add()?

Body:
I'm writing a library to create and manipulate Word .docx files in Python. In general, I take a lot of influence from the Microsoft VBA/C# API for Word in designing the API, figuring they've given it a lot more thought than I'll ever be able to. Several times I've found the wisdom in designing it the way they did only after getting much further down the road.

A table has the properties .rows and .columns, each of which is a sequence of the Row and Column instances in the table, respectively. In the MS API, the methods for adding a new one are Table.rows.add() and Table.columns.add().

I'm inclined to believe this is more complicated than necessary, making my API harder for beginners to learn without really providing any benefit.  I'm thinking Table.add_row() and Table.add_column() would better suit. As it happens, it also simplifies the code somewhat; that's not a motivator, just an observation that I wonder might be trying to tell me something.

Is there an argument for preferring the former?


答:
What you said in your comment has some importance. Maybe you could design some kind of hierarchy. Instead of everything referencing the application, have it reference some kind of parent object in hierarchy. Application can have UI windows/frames, those have controls. App can have documents, that too have some children, etc.. Maybe you could create something much more specific than everything referencing the application root object.

I would also agree with Telastyn. The object should have reference to it's parent if it uses this parent in some way. Don't go blindly add parent references to every object even if it doesn't use it.

Also, if you are thinking about memory consumption and counting bytes, then .NET is not a good pick.

Edit: After reading your comments, there are few things I would like to reply to:

About the consistency of traversal. Just because the object has reference to it's parent doesn't mean it has to expose it. Usually, such information is implementation detail. So from the outside, all objects are the same. From the inside on the other hand, there is problem with your mentality. You should think of object in almost complete isolation. Thinking that "when X object have Y, then all objects should have Y, because it is consistent" is not good, because it increases coupling and decreases cohesion.

"what's really so wrong with asking the application what the active document is and then doing something with said document?" Because it doesn't clearly express intent of the class, that it is requiring data that changes. If for example you used events and there was DocumentChanged event, that the class subscribes to and is pushed the new document, then that clearly states the intent of the class.

Finally, about your comment about technical stuff vs. patterns. Design patterns and principles are clearly technical thing. They are way to structure your code in a way that clearly expresses their intent and allows for easy maintenance and modification. If they weren't mentioned in any of those books, then those books are probably quite bad. Also, I recommend reading : What if I will not use Software Design Patterns?

And some nitpick: True engineer knows many tools, their strengths and weaknesses and knows when to use one over another. Saying you are fine with working only with one makes you look like a stupid code monkey instead of engineer.


问:
How to Name Different Branches with Identical Functionality in Semantic Versioning
For a software, I have two different branches, that only differ in using different library versions of a package, that my software uses. The API of this library has changed between the versions in a non-compatible way.

I am currently developping using both versions with the identical functionality in different branches, the only difference exists during building and loading of shared libraries.

Should I release these packages with different version names using Semantic Versioning? In my opinion, yes, but what about the naming of these different versions?

Currently I am using the "normal" numbering using the new version of the third-party library, e.g. 1.0.0, and a suffix for the version using the older third-party library, e.g. 1.0.0-json-c-0.10, see https://github.com/residuum/PuRestJson/releases

答:
In my company we are use Git tagging for that http://git-scm.com/book/en/Git-Basics-Tagging

This command lists the tags in alphabetical order; the order in which they appear has no real importance.

You can also search for tags with a particular pattern. The Git source
  repo, for instance, contains more than 240 tags. If you’re only
  interested in looking at the 1.4.2 series, you can run this:

```<code>$ git tag -l 'v1.4.2.*'
v1.4.2.1
v1.4.2.2
v1.4.2.3
v1.4.2.4
</code>```

Body:
In my company we are use Git tagging for that http://git-scm.com/book/en/Git-Basics-Tagging

This command lists the tags in alphabetical order; the order in which they appear has no real importance.

You can also search for tags with a particular pattern. The Git source
  repo, for instance, contains more than 240 tags. If you’re only
  interested in looking at the 1.4.2 series, you can run this:

$ git tag -l 'v1.4.2.*'
v1.4.2.1
v1.4.2.2
v1.4.2.3
v1.4.2.4


问:
Is a tree with nodes that have reference to parent still a tree?
If we make reference to the parent for each node in a tree, do we still have a tree (by definition) anymore?

Wikipedia definition is:

In computer science, a tree is a widely used abstract data type (ADT)
  or data structure implementing this ADT that simulates a hierarchical
  tree structure, with a root value and subtrees of children,
  represented as a set of linked nodes.

答:
A tree is a connected acyclic graph. In the case where we have "parent" links this would just be an undirected tree, but definitely still a tree. If you were to specify that the example is a directed graph it would not be considered a tree (but of course there's no way of telling from the code which was intended).

Some computer science "trees" will include, for instance, links from each node back to the root, or links along each level of a B+ tree. A computer scientist would probably still call these things trees, a mathematician would not.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
I have two ideas.

Often I find that I am repeating myself in catch blocks. This can be somewhat helped through extracting methods, but that can cause unnecessary clutter if the methods are very short or otherwise not worthy of a method. So, it would be nice to nest catch blocks:

```<code>try {
    // Save something
} catch (Exception e) {
    // Something we do for all Exceptions
    catch (ProcessingException e) {
        // Something we do for all Processing exceptions
        catch (DBExcpetion e) {
            // DBExceptions are a subclass of ProcessingException
        }
        catch (BusinessRuleException e) {
            // BusinessRuleExceptions are also a subclass of ProcessingException
        }
    }
    // Something we do after specific sub class Exceptions
 }
</code>```

In web programming I am also often find myself often doing something like this (this isn't a real example so don't analyze fictional cases):

```<code>Account a = getSavedAccount();
if (a == null) {
    a = getAccountFromSessionId();
}
if (a == null) {
    a = getAccountFromCookieId();
}
if (a == null) {
    a = createNewAccount();
}
</code>```

In Javascript (well, ECMAScript, and maybe others that I am unfamiliar with), since any value can be evaluated as a condition, || can help.

```<code>var a = getAFromLocation1() || getAFromLocation2() || default;
</code>```

I really like how that looks, and I wish more languages, particular some on the server side, had support for it. (PHP can evaluate anything as a condition, but converts the whole conditional expression to a boolean instead of preserving the value. I don't know about Python or Ruby.) It could get unwieldy after three cases or so, but if you have more than three cases, you might also have a bad software design.

Body:
I have two ideas.

Often I find that I am repeating myself in catch blocks. This can be somewhat helped through extracting methods, but that can cause unnecessary clutter if the methods are very short or otherwise not worthy of a method. So, it would be nice to nest catch blocks:

try {
    // Save something
} catch (Exception e) {
    // Something we do for all Exceptions
    catch (ProcessingException e) {
        // Something we do for all Processing exceptions
        catch (DBExcpetion e) {
            // DBExceptions are a subclass of ProcessingException
        }
        catch (BusinessRuleException e) {
            // BusinessRuleExceptions are also a subclass of ProcessingException
        }
    }
    // Something we do after specific sub class Exceptions
 }

In web programming I am also often find myself often doing something like this (this isn't a real example so don't analyze fictional cases):

Account a = getSavedAccount();
if (a == null) {
    a = getAccountFromSessionId();
}
if (a == null) {
    a = getAccountFromCookieId();
}
if (a == null) {
    a = createNewAccount();
}

In Javascript (well, ECMAScript, and maybe others that I am unfamiliar with), since any value can be evaluated as a condition, || can help.

var a = getAFromLocation1() || getAFromLocation2() || default;

I really like how that looks, and I wish more languages, particular some on the server side, had support for it. (PHP can evaluate anything as a condition, but converts the whole conditional expression to a boolean instead of preserving the value. I don't know about Python or Ruby.) It could get unwieldy after three cases or so, but if you have more than three cases, you might also have a bad software design.


问:
Two months in my new job, still having trouble learning a new codebase. How can I improve?
I'm a self-taught programmer. Up until now I haven't had too much problems building things I have wanted to. Historically, given an issue, especially one I have caused I haven't had much of a problem figuring it out. This all changed about two months ago, when I was offered my first position at a company whom I became acquainted with after a pull request to a framework they use.

I relocated for the position and I really like the environment, it's a small team of about ten people, and from what I can tell they all seem to be incredibly talented. They gave me a pet project to do in which I had mostly full autonomy over. They stressed that they dont expect developers to become entirely productive and profitable until about the 3-6 month marks and that this project would help them understand where I'm at as a developer. It felt great and after a month I was put on one of their bigger projects on one of their most longstanding contracts.

After switching to this project I felt kind of overwhelmed, it is a LARGE codebase where changes are very visible to our clients clients, as it powers a number of sites. It is also a very complex codebase, while I attribute a lot of my hardship to my lack of experience it was originally a rescue project, syncs everything between two seperate frameworks and has a number of models that do thing I cannot given my experience understand, has no documentation, and a test coverage of 85%. I was originally tasked with making a few small changes, things like implementing honeybadger notifications on mail delivery failures, or rewriting minitest tests to rspec specs.

Then I was tasked with upgrading one of the frameworks that the project depends on. This has taken me an abnormally large amount of time, and I was retasked to something else until one of the senior developers comes back from holidays to act as a support system during the process. The task I was reassigned to turned out to be giving me an equally large amount of trouble.

I had a sit down with my employers and talked to them about this. They stated that it's normal given my experience and that I currently meet their expectations. However, this is the first time in my life I really could not do what I set out to in any amount of reasonable time. Is this a feeling that is shared among others, is it a normal occurrence?

What would be the expected amount of time to become acquainted wit a large codebase of say 50,000 lines? Are there any other practices that I may not know about that could help me become familiar with a codebase faster?

答:
You said you're a self-taught programmer and by this question I assume you don't have prior experience with such big projects.

Personally, I have less experience than you so do not take my words as gift of god.
Honestly, I think it's perfectly normal to be overwhelmed from such big projects when you don't have prior experience. If they expressed already that you meet their expectations then you really shouldn't worry about it so much.

As you said there's no documentation, try to improve the documentation if they allow you to. That would make everyone a favour for sure.

TLDR; Give it time. Get used to it. Don't be afraid to ask questions and take it positively - in a year or two you'll laught at it wondering how the hell you couldn't underestand such simple code.


答:
You say it yourself: I'm a self-taught programmer.  Books and linear courses got you this far, but have reached their limit.  Time to dispense with passive instruction. Get serious: get formal teaching.

Most people improve significantly when they engage a teacher: someone who can look at you subjectively and focus on your personal strengths and weaknesses.  That might mean a course at a school, sitting next to a more experienced colleague who is happy to help you, or even a modern online course that provides subjective feedback.

Title: Two months in my new job, still having trouble learning a new codebase. How can I improve?

Body:
I'm a self-taught programmer. Up until now I haven't had too much problems building things I have wanted to. Historically, given an issue, especially one I have caused I haven't had much of a problem figuring it out. This all changed about two months ago, when I was offered my first position at a company whom I became acquainted with after a pull request to a framework they use.

I relocated for the position and I really like the environment, it's a small team of about ten people, and from what I can tell they all seem to be incredibly talented. They gave me a pet project to do in which I had mostly full autonomy over. They stressed that they dont expect developers to become entirely productive and profitable until about the 3-6 month marks and that this project would help them understand where I'm at as a developer. It felt great and after a month I was put on one of their bigger projects on one of their most longstanding contracts.

After switching to this project I felt kind of overwhelmed, it is a LARGE codebase where changes are very visible to our clients clients, as it powers a number of sites. It is also a very complex codebase, while I attribute a lot of my hardship to my lack of experience it was originally a rescue project, syncs everything between two seperate frameworks and has a number of models that do thing I cannot given my experience understand, has no documentation, and a test coverage of 85%. I was originally tasked with making a few small changes, things like implementing honeybadger notifications on mail delivery failures, or rewriting minitest tests to rspec specs.

Then I was tasked with upgrading one of the frameworks that the project depends on. This has taken me an abnormally large amount of time, and I was retasked to something else until one of the senior developers comes back from holidays to act as a support system during the process. The task I was reassigned to turned out to be giving me an equally large amount of trouble.

I had a sit down with my employers and talked to them about this. They stated that it's normal given my experience and that I currently meet their expectations. However, this is the first time in my life I really could not do what I set out to in any amount of reasonable time. Is this a feeling that is shared among others, is it a normal occurrence?

What would be the expected amount of time to become acquainted wit a large codebase of say 50,000 lines? Are there any other practices that I may not know about that could help me become familiar with a codebase faster?


答:
How long for ~50kloc? Maybe 2-3 weeks. of course it will take longer if you're also learning the language, framework or tools. The key thing to realize is that you're meeting your employer's expectations. There's no need to stress out too much, as that will lead to mistakes.

What can you do? Experiment. Tinker. Fiddle.

Take the codebase and change something to see how it works - and see what it breaks. You said the codebase has good test coverage, so you should have good visibility into how your changes impact the code.

If you encounter something you don't know, do some research to learn about it, but then make a prototype. Take that new concept and toy with it in a safe environment where you don't feel the pressure of work or client demands.

The best way to learn something is to work with it.


答:
Should I release these packages with different version names using
  Semantic Versioning? In my opinion, yes, but what about the naming of
  these different versions?

You should not change the version unless your code changes. However, your current approach of appending the library version works fine under the rules of Semantic Versioning, but you have to use a + sign to add the library dependency:

1.0.0

1.0.0+json-c-0.10

For realeasing, and assuming your package name is purestjson this gives:

purestjson-1.0.0

purestjson-1.0.0+json-c-0.10

Rationale: Semantic Versioning states in rule 10:

Build metadata MAY be denoted by appending a plus sign and a series of
  dot separated identifiers immediately following the patch or
  pre-release version. Identifiers MUST comprise only ASCII
  alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
  Build metadata SHOULD be ignored when determining version precedence.
  Thus two versions that differ only in the build metadata, have the
  same precedence. Examples: 1.0.0-alpha+001, 1.0.0+20130313144700,
  1.0.0-beta+exp.sha.5114f85.

Title: How to Name Different Branches with Identical Functionality in Semantic Versioning

Body:
For a software, I have two different branches, that only differ in using different library versions of a package, that my software uses. The API of this library has changed between the versions in a non-compatible way.

I am currently developping using both versions with the identical functionality in different branches, the only difference exists during building and loading of shared libraries.

Should I release these packages with different version names using Semantic Versioning? In my opinion, yes, but what about the naming of these different versions?

Currently I am using the "normal" numbering using the new version of the third-party library, e.g. 1.0.0, and a suffix for the version using the older third-party library, e.g. 1.0.0-json-c-0.10, see https://github.com/residuum/PuRestJson/releases


问:
How can I automate production deployments without experiencing extreme anxiety?
At our shop we use SVN for source control and CruiseControl for CI on handling automatic builds and deployments to our development, test, and integration environments.

This all works smoothly however due to hardware and resource constraints our integration environment is not a 2 server load balanced environment like our production environment.  While everything else is equal that would be the only difference between our integration and production environments (although a big one!)

Theoretically the difference is a slightly different configuration of our app servers and the deploy script merely would have to drop the build artifacts into two servers instead of just the one, but why am I so nervous to automate our production deployments?!

I am generally not a control freak but I always feel the insatiable need to deploy production to production manually.  I have heard from colleagues that this is generally a Really BAD Thing™ but they failed to make a case against it.

I know that when I do it manually I can SEE that I am physically copying the correct files, I am physically shutting down the app servers and ensuring they closed successfully, I am physically starting the servers back up and then physically inspecting the logs to make sure it started up okay and the deployment was successful.  It gives me a peace of mind.

What are arguments against this OR arguments for automatic scripted production deployment?

答:
take a larger window for deployment the first time if things goes wrong

Divide the Deployment process in two parts.
a. Backup (manual) - this should give you confidence if anything goes wrong during deployment

b. Deployment(automated)

once you are able to deploy with confidence for the first time. you can automate the backup process as well.


答:
I have had good success to learn new code bases with the following approach. Strive to understand:

Purpose: understand what the system or framework does, conceptually speaking

Architecture: create a view on the overall architecture of the system or framework

Components: learn how major parts (components) work together

Code: now you are ready to take deep dives by debugging major flows through the code base, e.g. while fixing a bug

Here's the rationale for each of these steps, and how you could approach them. Note it may take you several iterations going from step 1 to 4. Take your time.

Purpose

This may sound obvious, yet I find that even experienced developers sometimes lack a basic understanding of what the system's main purpose is. Strive to learn the business concepts *) free from technology first (i.e. ask questions like: "this system processes customer orders and issues invoices -- what is a customer, how do orders and invoices look like, what does it mean to issue an invoice? Who is using the system? What do they need to do with it?" etc.)

*) "business" meaning: from the customer's or user's point of view

Knowing the conceptual level without specifically looking at technology is a major plus in getting to understand its inner most workings -- code is merely a means to an end and without knowing the end all code is essentially meaningless, and so it will appear. If you don't have a conceptual understanding yet, ask someone to explain. If you think you do, explain it to someone more senior on the project. You will learn a lot either way.

Architecture

Next, strive to understand the overall architecture. This is at a technology level, but without looking at the detail implementation. Examples of the architecture level are:

tiers - e.g. web tier, business tier, database tier, front-end, backend, ...

layers - e.g. user interface, business model, service interfaces, ORM,...

major components - e.g. order processor, invoice generator, customer manager, ...

infrastructure - e.g. network setup, servers, message queues,

Again, if you don't know any of this yet, ask someone to give you an overview (within at most 1-2 hours to avoid getting lost in details). You will benefit from documenting the results of such an introduction, start with simple diagrams first (maybe using Visio or similar tools), and over time develop the ability to use a more formal approach such as UML. The process of documenting may sound tedious and useless, yet it is uterly useful as it is not the result that counts but the thinking process that goes into drawing the diagrams.

Components

Looking at the major components, understand how they work together to achieve the purpose of the system. Go back to the conceptual level and map the concepts and what users do to each of the components. Draw flow charts or sequence diagrams to see how data flows through the system. Again the main purpose of drawing is not the diagrams as such, but to force your brain to think it through.

This is also a good time to map components to code. Usually such components are made of several parts (e.g. several programs, classes, database scripts or whatever code artifacts your system uses). It is good enough to understand, for each component, where the respective code is located -- later on you can still dive into details.

A note of caution: it may be that your co-workers don't have a notion of "components" other than actual code artifacts -- that's not untypical if someone is deeply immersed with the code base. Try to ask questions such as "looking at the code base overall, are there areas such as programs/packages/classes that belong together? What is their purpose, as a group? Which of these need to work toegether to achieve X?"

Code

Take one particular entry point into the system - e.g. a user interface, a web service, an API etc. and set up a debug session. Then step through the code, always paying attention to which component the currently executed code belongs to. In your mind, map this actual flow back to your earlier flow charts and maybe update them if you find missing gaps.

Instead of stepping through the code in a debug session you could also use a profiler. That is, a program that records the flow for you and displays a hierarchy of all subroutine calls.

Another alternative is to use a code analyzer / reverse engineering tool that is able to decern a hierarchy of dependencies. However in my experience these tools generate too much data to be useful for the novice, that's why I would prefer the debugging approach.


答:
There is so-called "Dijkstra's Loop" (also called "Dijkstra's Guarded Loop"). It was defined in The Guarded Command Language (GCL). You can find some information about it syntax and semantic in the above Wikipedia article at the section 6 Repetition: do.

Nowadays I actually know one programming language which supports this control struture directly. It is Oberon-07 (PDF, 70 KB). And it supports "Dijkstra's Loop" in thу form of while statement. Take a look at section 9.6. While statements in the above PDF.

```<code>WHILE m > n DO m := m – n
ELSIF n > m DO n := n – m
END
</code>```

P.S. This is copy of my SO answer.

Title: Which useful alternative control structures do you know?

Body:
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

Body:
There is so-called "Dijkstra's Loop" (also called "Dijkstra's Guarded Loop"). It was defined in The Guarded Command Language (GCL). You can find some information about it syntax and semantic in the above Wikipedia article at the section 6 Repetition: do.

Nowadays I actually know one programming language which supports this control struture directly. It is Oberon-07 (PDF, 70 KB). And it supports "Dijkstra's Loop" in thу form of while statement. Take a look at section 9.6. While statements in the above PDF.

WHILE m > n DO m := m – n
ELSIF n > m DO n := n – m
END

P.S. This is copy of my SO answer.


答:
I think your question is a bit opaque because there are different kinds of errors.

Connection/authentication/location errors

One part (which you handle most of the time upfront) if errors like: 404 not found, 401 unauthorised etc. Those are most of the time breaking and returned directly.

Redirects and other locations

Also things like 302 moved permanently may be covered before real data processing.

Content of message errors

If all of this is satisfied you get to the real content of the message:

Example: You have errors in the sent in data: 422 unprocessable entity (from webdav standard). For that you might need to start real processing. Reading, parsing the message. Validating it's contents etc.

Only for that last part we use aggregated errors, because we say the message is invalid and we want to be clear about: "Ok it's wrong, so what is wrong with it?"

For example see: https://stackoverflow.com/questions/15310649/should-http-status-be-used-in-restful-error-responses which covers that part.

Conclusion

So generally: We do not combine the basic errors, we send only one and try to handle this in order of the specification. So don't combine: 401 not authenticated with 302 moved permanently. It would not make sense. The client gets 401 unauthenticated and that's it. If it fixes that it gets the 302 moved permanently.

For the content we send a list (in json for example) with the wrong data sent in and what is wrong with it.

Title: Should I Aggregate Web API Errors?

Body:
The Situation

We are writing a REST API that performs validation up-front.
The code is written such that it tries to find as many errors as possible.
However, each error might correspond to a different HTTP status code.
Additionally, the client (the HTML) doesn't have a convenient way to parse/display the errors.

The Question

Is it better to just throw as soon as the first error occurs?
Or should we do our best to aggregate the errors somehow?
By the way, there is no requirement to try to handle as many as possible at once.

I am not looking for an opinion.
I was curious if there was a standard practice in REST.

Why It Matters

The current code is really complex.
Some validation can only be run if other pieces are valid.
So there is this explicit dependency between tests.
It is complex enough that it warrants using a 3rd-party library.
But I would rather just eliminate the cause of the complexity if I am going to spend time on it.


问:
Scrum decision making versus maintainability and development time?
I appreciate that this question may be controversial. In a sense, it is the flip-side of the question "Business trying to make technical decisions".

In Scrum, the development team is supposed to be collectively responsible for making design and technical and code-level decisions, to fulfill the customer requirements. There is a division of responsibility and power between the product owner, who defines and prioritises the stories by communicating with stakeholders, and the team, who decide how to implement the stories.

I think this is motivated by the belief that, since developers are intimately familiar with the code they have written so far, and all the information they have memorised or noted about the project, and they will face the consequences of poor decisions when they have to modify the code in future, they are best placed to make design decisions. And if in hindsight they realise they made a bad decision, it will be a very valuable learning experience for them, and they won't be able to blame management for what went wrong. In theory, I agree with all this. But (to kind of play devil's advocate) I can see several situations in which following this principle to the letter could be a bad idea:

The development team are mostly either temporary contractors, are (unbenownst to others) intending to jump ship, or are going to be made redundant after shipping this project, or are going to move to another project and there is an entirely separate team which will do "code maintenance". (A good example of this might be: a typical outsourced government computerisation project.) So, for any of these reasons, the team mostly aren't the people who will be doing the actual maintenance.

Or, the development team are all inexperienced developers who don't really have a clear idea of the maintainability problems that can be caused by slipshod development practices or poor design decisions. While they have an incentive in theory to do the right things, the incentive isn't working yet because they haven't been burned enough times (or they haven't acknowledged the connection between sloppy coding practices and getting burned).

The development team like making big mistakes and working crazy hours to fix or work around them because (a) they are workaholics, (b) they like wasting time writing boilerplate code or using some bad old framework because it gives them a sense of job security, or (c) it makes them look like or feel like heroes.

The team like to endlessly bikeshed, or discuss endless different permutations of ideas, or add "internally-visible features" which are low-value, while the business really needs them to deliver value faster, and come on, good enough is good enough!

There may be others in the organisation who could provide a variety of useful inputs into design and technical decisions: More experienced developers; Polyglot developers; Specialists, including DBAs (who may not necessarily be in the scrum team); Managers, who may be cynical and may have seen over-ambitious or wrong-headed architectures go awry too many times.

But it's not just about getting input from people with valuable experience. More than this, isn't it fundamentally sometimes necessary for management (at any level) to be able to say "No, this way of implementing it would be a bad idea. Do it this way instead", or at least "No, you can try that later if there's time, but do it this simpler way initially"? It seems to me that Scrum is too idealistic in this respect. I know that this does happen, obviously, but to say that because of this interference "your organisation is not doing Scrum" suggests that "doing Scrum" is not desirable in such cases!

答:
It sounds like what you're saying boils down to:

A self-managing, self-designing Scrum team only exists when the entire team is experienced and committed.

In more realistic situations, management should be allowed to manage the team and influence design decisions in order to avoid bigger problems.

If this is right, then the problem isn't with Scrum, but with how your team has adopted it.  Either

It's still early and everyone is still learning to be efficient Agile team members; or

Agile and Scrum aren't a good fit for the team's personality; or

Agile and Scrum aren't a good fir for the project demands; or, more likely

Agile and Scrum aren't compatible with current Management's concept of management.

Scrum and Agile aren't only about iterative software releases.  It's also about improving the software development lifecycle.  Each iteration should bring improvements to the application and, equally important, to the development process as well.  This means there's going to be a period up front where things may not work all that well, but if you're team is on board, things will get better.

IF your team is on board.  I've seen Scrum fail simply because somebody wouldn't play ball.  Suddenly, the efforts of 5 people to be Agile are completely derailed because one other person's incentives don't line up with the Agile/Scrum ethos.  Don't be that person!  You may not like what's going on, but why is that?  Is there a real problem?  Is the team simply not adopting Agile effectively, or is this new approach simply still foreign and scary?

It is quite possible that you are perfectly comfortable with Agile and Scrum, and that your team is indeed failing at improving or delivering.  In this case, you can either decide to ditch Agile development, or invest more time and effort in fixing the problem.  Do you have a Scrum Master?  Does everyone in the team understand what Agile development is?  People usually shy away from Agile development when they think it will make them more vulnerable or liable.  This shouldn't be the case, but sometimes people feel that way...

Or, even worse, sometime's it's even true.  Ask yourself if Agile/Scrum/iterative software development actually makes sense in your situation.  If not, adopting it might put your team under undue stress.  I've seen projects follow iterative development when Waterfall would have suited everyone much more.  Don't simply adopt iterative development because it's the -in- thing.  Make sure it fits your project/business.  If it does, great!  If it doesn't, find a development and management style that does.

But, ultimately, if you do chose to follow an Agile/Scrum approach, make sure everyone is properly educated on the process, the tools, the goals, the advantages, and the sacrifices.  In your situation, it seems like people are forgetting that a highly iterative process can sacrifice Design and Architecture in the short term because sprints react to the ever evolving needs of the Product Owner.  But these are short term sacrifices.  Your team should ask for hardening sprints to chip away at their accumulated debts (whether they be technical, architectural, testing, etc).  That's how Agile development balances reactivity and maintainability.

whew.  I think that's all for now!


问:
Is thinking out loud during an interview really the best strategy?
In another question I asked recently about best practices for whiteboarding, there was general consensus that thinking out loud while coming up with the answer was the best strategy.

Indeed, long moments of silence are awkward.

However after recent interviews I have noticed that if my thinking out loud leads to wrong solutions or down the wrong path, that with further consideration I would have seen, interviewers tend to quickly jump in and point out problems with my approach, especially if I stop to pause for a minute. This was not an isolated case, and happened during more than one interview with more than one interviewer.

The other thing is that after the interview, on a problem I absolutely bombed, when I sat down and sketched out the problem on a piece of paper in silence I was able to sketch out the solution pretty quickly. Thinking out loud ends up with me spending brain cycles on reflecting on how what I say must be registering with the interviewer and in addition there's a fear of recognizing that I've gone down the wrong path and starting over after having written something on the board wastes a lot of time. Once you've started down one path and realize you've written a lot of junk, you can't undo it, whereas if you've thought quietly about it the interviewer wouldn't have seen the mess and it would have been quicker since whiteboarding a bad idea takes up more time than simply considering a bad idea.

I don't want moments of silence but at the same time speaking takes more time, leads to self-consciousness and can lead to interviewer intervention on something I might have figured out myself with just a little more time.

答:
My recent experience with whiteboarding a problem leaves me feeling abused and certain that the interviewer only learned a few things about my childhood traumas and nothing about my capabilities.

I don't think it is a good idea, or even ethical, to stick a pin in a technical genius and display him in front of a whiteboard.

Next time! I will bring a notepad and a colored pen or two and do what I normally do to solve a problem. I start sketching preschool squiggles until my brain goes into hyperdrive. Hopefully, I will relax enough to start thinking. It seems that my fear is that I will fail miserably and that fear fails me miserably. Maybe practice will help.


答:
You can try abolishing the Application altogheter, which means now some of your objects would be unable perform their job, having no way of reaching their colaborators.

Then, you start passing along only the objects really needed for your object to perform its work. Say, using your example of a "Paste" plugin (in the comment here), it needs a document in order to do his job, so you pass a document.

I think this is referred as the Law of Demeter, ask you want, not the thing on which you will find the thing you want, i.e. only depend on things really related to your single responsability.

When you pass the application to your plugin, you're unnecessarily coupling things togheter. If for some reason you'd want to change the active document discovery mechanism, you'd be in risk of breaking some plugin. Now, if you have hundreds of plugins depending on things like that, you end up wasting a vast amount of time fixing them, or you don't change it, which means you can't refactor, and the codebase may rot by workarounds.

Of course, in the example of your plugin maybe you need some other things, and maybe you would need some kind of uniformity. Still you don't need to pass along the full aplication, you can define an interface with only the things plugins (or a certain type of plugin) needs, and then use it (Interface Segregation Principle).

Let's say, your application has this methods:

```<code>interface Application {
    void quit();
    void openSaveAsDialog();
    Document getActiveDocument();
}
</code>```

If your plugins are not intended to use quit or openSaveAsDialog, then you can define something like:

```<code>interface Benchwork {
    Document getActiveDocument();
}
</code>```

For the plugins, you can still implement Benchwork in terms of calling Application, but you can probably break Application in several smaller pieces (several nested subsystems, like a bench, containing a display, containing views, one of which is as an editor which deals with documents, composed of elements (images/paragraphs/attachments) etc), and have Application to be a really thin high-level thing.

Not an architect myself, but the downside I can see, is that you will probably end up with far more classes and interfaces in your project, but as they make things more manageable, not sure if that is really a problem.

You may want to check the google clean code talks (which is mostly about dependencies and how to make them testable).

Body:
You can try abolishing the Application altogheter, which means now some of your objects would be unable perform their job, having no way of reaching their colaborators.

Then, you start passing along only the objects really needed for your object to perform its work. Say, using your example of a "Paste" plugin (in the comment here), it needs a document in order to do his job, so you pass a document.

I think this is referred as the Law of Demeter, ask you want, not the thing on which you will find the thing you want, i.e. only depend on things really related to your single responsability.

When you pass the application to your plugin, you're unnecessarily coupling things togheter. If for some reason you'd want to change the active document discovery mechanism, you'd be in risk of breaking some plugin. Now, if you have hundreds of plugins depending on things like that, you end up wasting a vast amount of time fixing them, or you don't change it, which means you can't refactor, and the codebase may rot by workarounds.

Of course, in the example of your plugin maybe you need some other things, and maybe you would need some kind of uniformity. Still you don't need to pass along the full aplication, you can define an interface with only the things plugins (or a certain type of plugin) needs, and then use it (Interface Segregation Principle).

Let's say, your application has this methods:

interface Application {
    void quit();
    void openSaveAsDialog();
    Document getActiveDocument();
}

If your plugins are not intended to use quit or openSaveAsDialog, then you can define something like:

interface Benchwork {
    Document getActiveDocument();
}

For the plugins, you can still implement Benchwork in terms of calling Application, but you can probably break Application in several smaller pieces (several nested subsystems, like a bench, containing a display, containing views, one of which is as an editor which deals with documents, composed of elements (images/paragraphs/attachments) etc), and have Application to be a really thin high-level thing.

Not an architect myself, but the downside I can see, is that you will probably end up with far more classes and interfaces in your project, but as they make things more manageable, not sure if that is really a problem.

You may want to check the google clean code talks (which is mostly about dependencies and how to make them testable).


答:
I'm not a C developer, so please excuse the terminology errors.

Semantic Version and code branches (including 3rd party code)

From a Semantic Versioning perspective I think there are a few ways your can approach the version naming and its really up to you how you might like to approach it from within a GIT repo for a C project.

In your case, the API reached version 1.0.0, and it looks like your creating a different build option for allowing the users to use previous editions of some of your library code. Your in a spot, where your offering a regression to an older edition or code. I see that as a minor change as per rule 7:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

Rule 10, implies that you should include '+Alpha', '+Beta', '+RC' or '+RTM' or [BLANK] rather than the 'json-c-0.10' you have chosen in your Git Repo. Further more if you were to continue to use 'json-c-0.10' approach and you have multiple other libraries within your API, you could end up with a really long file name. I've also seen '+Dev', '+Nightly', '+Stable' included in names to help developers testing the code.

Have a look at using your MakeFile that configures the output to generate various folders that represent how the API file is compiled with various options. Notice the output file name is the same, just stored in a different folder. For example:

/Output/Linux/Nightly/purestjson-1.1.0.exe

/Output/Mac/Nightly/purestjson-1.1.0.exe

/Output/Windows7/Nightly/purestjson-1.1.0.exe

/Output/*/Stable/purestjson-1.1.0.exe

/Output/*/Old/purestjson-1.1.0.exe

/Output/*/Custom/purestjson-1.1.0.exe

Folder Definition examples

You can then provide the API community which MakeFile Target for the Custom 3rd party code combinations.

Nightly - Might include all the raw code Git pushes from all the 3rd party libraries.

Stable - Code from the 3rd party library current releases.

Old - Code from the 3rd party library previous releases.

Custom - Allows the user to pick and choose which edition of a 3rd party library they would like to use.

Review how your using Git with branches, feature, releases and bug fixes. There is a git extension you might find useful called GitFlow and an popular approach by Vincent Driessen discussed in his 'Successful GIT Branching model' article. Atlassian provide a GUI for Windows/Mac that includes GitFlow called SourceTree.

One thing you might also want to think about is using a Continous Integration server to compile the software and include "+IncrementalBuildNumber' or '+YYYYMMDD' to help with unit testing.

Breaking API Changes

This is a common issue for API developers. I've seen a few solutions to the issue.

Let it break by removing the old methods. Not very community friendly

Create compiler warnings for obsolete API methods. In the .NET World you can include information for the software developer explaining how to migrate the old methods to new methods or links to web pages explaining it. This will help your API community to understand what to change from/to.

Where possible, retain the old methods and use the new API calls within those obsolete methods, while warning the developer via compiler warnings that the code will be remove at a future time (recommend at the next major release). This allows the developers a "Major" version release cycle to get there code in order. Essentially your giving your API Community a chance to remove redundant API calls without breaking there builds immediately. Optimal solution that allows warnings without compile failures but at the expense of code bloat.