问:
Manual memory allocation and purity
Language like Haskell have concept of purity. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here.

But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless.

How should I handle purity in languages have memory as visible global object?

答:
I have to disagree with the basic premise.

C++ (to use your example, though the same would apply to C, Pascal, Ada, etc.) doesn't give any real visibility into the heap. You can attempt to allocate some memory, which might succeed or fail -- but you have no visibility into why an allocation succeeded or failed, nor what other allocations may have lead to that success/failure.

In other words, allocating some memory in one place does not have an effect that's directly visible anywhere else. Yes, it's possible one allocation could lead to the failure of another, but 1) noting in portable C++ can put those together, and 2) it's usually next to impossible to make that connection even in a non-portable way.

In the other direction, nothing in Haskell (or any other language) can change the fundamentals involved anyway. Attempting to allocate more memory than is available (even as virtual address space) will fail, regardless of the language. If the user runs another program that hogs all the memory, neither C++ or Haskell (or much of anything else) can do much about that, so an allocation that would succeed in one run may fail in another.

In fairness, I suppose I should add that even though it's not portable, many (most?) heap managers include extra functions to walk the current heap, see what blocks are allocated, etc. Yes, I suppose such a thing could be seen as breaking "purity", but my guess is that people including heap-walking in their software probably aren't bothered a lot by that (and those who really care about purity just don't use that capability.

Title: Manual memory allocation and purity


答:
I think you're asserting too much when you say that "making new objects" being impure implies that almost nothing can be pure.  If you isolate your memory allocation from your mainline logic, then the main-line logic can be made as "pure" or "impure" as the situation demands.  A technique I use regularly is to define data manipulation functions that leave the this object untouched, but that take a parameter for a destination in which the results should be placed.  (Often, I allow the destination to be the same as the this object.)  For example,

```<code>class Countdown
{
private:
    int _CountLeft;
public:
    void init(int CountLeft) { this->_CountLeft = CountLeft; }
    int getCountLeft() const { return this->_CountLeft; }
    bool decrease(Countdown &Dest) const {
        Dest._CountLeft = this->_CountLeft - 1;
        return Dest._CountLeft > 0;
    }
};
</code>```

I'm aware that this isn't idiomatic C++ (more on that in a bit), but it is a way of implementing pure functions in C++.

Now, I'll try to explain some odd features of the class:

Why use an init method, instead of a constructor?

I deliberately wanted to remove any memory management concerns from this object's specification; using a constructor or destructor introduces some functional dependence of the class's behavior on memory allocation / release.

How is this function "pure"?

It is "pure" in the sense that, if we always give a new instance of the object as a destination parameter, then the input data to any operation never changes.  For example:

```<code>Countdown CountdownArray[10];
CountdownArray[0].init(5);
for(
  int Index = 0;
  Index < 10 - 1 &&
    CountdownArray[Index].decrease(CountdownArray[Index+1];
  Index++)
{
    continue;
}
</code>```

Well, obviously this behavior is not "pure", exactly, but the elements of CountdownArray have not been modified since their first initialization; the decrease method does behave in a pure fashion, when given an appropriate destination parameter.

How can I manage the memory for this class effectively?

In this case, the class is written such that the Dest parameter can be the same object pointed to by this:

```<code>Countdown CD;
CD.init(5);
while(CD.decrase(CD))
{
}
</code>```

This obviously makes the behavior less "pure", but also makes the generated code significantly more memory-efficient.

How does this technique interact with inheritance?

Good question.  I avoid inheritance when using this technique.

Conclusion

A general-purpose computer cannot practically be "pure" - we have a finite amount of resources to work with in a computer (memory, disk space, CPU registers), and efficient use of these resources requires that they be mutable.  What people mean by "purity" in computing is that we've isolated the immutable from the mutable, and the immutable state can be considered "pure".  You're correct that memory allocation can have side effects on other parts of the system (e.g. by causing later allocations to fail as we run out of memory).  But it can be practical to factor out the memory allocation from the code that we want to be pure.

ContentLicense: CC BY-SA 3.0

Title: Manual memory allocation and purity

Body:
Language like Haskell have concept of purity. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here.

But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless.

How should I handle purity in languages have memory as visible global object?

Body:
I think you're asserting too much when you say that "making new objects" being impure implies that almost nothing can be pure.  If you isolate your memory allocation from your mainline logic, then the main-line logic can be made as "pure" or "impure" as the situation demands.  A technique I use regularly is to define data manipulation functions that leave the this object untouched, but that take a parameter for a destination in which the results should be placed.  (Often, I allow the destination to be the same as the this object.)  For example,

class Countdown
{
private:
    int _CountLeft;
public:
    void init(int CountLeft) { this->_CountLeft = CountLeft; }
    int getCountLeft() const { return this->_CountLeft; }
    bool decrease(Countdown &Dest) const {
        Dest._CountLeft = this->_CountLeft - 1;
        return Dest._CountLeft > 0;
    }
};

I'm aware that this isn't idiomatic C++ (more on that in a bit), but it is a way of implementing pure functions in C++.

Now, I'll try to explain some odd features of the class:

Why use an init method, instead of a constructor?

I deliberately wanted to remove any memory management concerns from this object's specification; using a constructor or destructor introduces some functional dependence of the class's behavior on memory allocation / release.

How is this function "pure"?

It is "pure" in the sense that, if we always give a new instance of the object as a destination parameter, then the input data to any operation never changes.  For example:

Countdown CountdownArray[10];
CountdownArray[0].init(5);
for(
  int Index = 0;
  Index < 10 - 1 &&
    CountdownArray[Index].decrease(CountdownArray[Index+1];
  Index++)
{
    continue;
}

Well, obviously this behavior is not "pure", exactly, but the elements of CountdownArray have not been modified since their first initialization; the decrease method does behave in a pure fashion, when given an appropriate destination parameter.

How can I manage the memory for this class effectively?

In this case, the class is written such that the Dest parameter can be the same object pointed to by this:

Countdown CD;
CD.init(5);
while(CD.decrase(CD))
{
}

This obviously makes the behavior less "pure", but also makes the generated code significantly more memory-efficient.

How does this technique interact with inheritance?

Good question.  I avoid inheritance when using this technique.

Conclusion

A general-purpose computer cannot practically be "pure" - we have a finite amount of resources to work with in a computer (memory, disk space, CPU registers), and efficient use of these resources requires that they be mutable.  What people mean by "purity" in computing is that we've isolated the immutable from the mutable, and the immutable state can be considered "pure".  You're correct that memory allocation can have side effects on other parts of the system (e.g. by causing later allocations to fail as we run out of memory).  But it can be practical to factor out the memory allocation from the code that we want to be pure.


问:
Any basic difference between Unix and Linux in design and other aspects?
I keep reading this sentence:

Linux is a Unix-like system, but it is not Unix.

I don't know what's the real difference between the two. I know Linux got a lot of ideas from Unix and the licenses of the two are different. Apart from that, as I am not an expert in either one of them, I want to know whether there are basic differences between them in design or other significant aspects.

答: Not really, Linux was a cobbled together reverse engineering of Unix after all, so the kernel design followed Ken Thompson's philosophy. The Linux way seems to be to imitate Unix philosophy as closely as possible without ever burdening ones self with original thought. </p>


答:
"UNIX" is a complicated thing to pin down. In terms of standards conformance, both Solaris and Mac OS X are "officially" UNIX but you don't have to spend much time before you find rather large differences between the two. There's a great diagram that documents the release of various flavours of UNIX or UNIX-like operating systems and how they influenced and diverged from each other.

In the grand scheme of things that look, walk and quack like UNIX, a Linux system [*] is one of the more conventional releases. It's quite common for people to refer to Unices or *nix and mean "anything UNIX-like", which probably includes Linux. However UNIX is a registered trademark with limitations on how it may be applied commercially; no Linux distribution conforms to those limitations.

[*]Because this question invites a level of semantic hair-splitting I think it's on-topic in this case to point out that Linux itself is just a kernel on which an operating system can be built. It's common to build a UNIX-like system on top of Linux, which is what it was designed for, and that system is usually built out of GNU project components. In the answer above "Linux" could be read as shorthand for "an operating system that incorporates the Linux kernel".

Title: Any basic difference between Unix and Linux in design and other aspects?

Body:
I keep reading this sentence:

Linux is a Unix-like system, but it is not Unix.

I don't know what's the real difference between the two. I know Linux got a lot of ideas from Unix and the licenses of the two are different. Apart from that, as I am not an expert in either one of them, I want to know whether there are basic differences between them in design or other significant aspects.


问:
OOP - Composition, Components and Composites Example?
I've been reading a bit about OOP in relation to Composition, Components and Composites. I believe I understand the fundamental principle (not sure).

Can someone please provide a code example of a person or car (both have many properties) using Composition, Components and Composites? I think seeing it in code would clear up the confusion I have regarding this pattern.

Preferably in Java or PHP.

答:
I am not a Java programmer, although I've dabbled in it a little, however I think the Java Swing framework is the only real world example of the Composite Pattern which I've ever used.

In short, Swing uses the concept of 'Containers', which are designed to hold GUI components/widgets - some of the components/widgets which can be stored are themselves containers;  this is where the composite pattern exists.

e.g. a Panel container might contain a LayoutManager container, which in turn might contain several panels and several other LayoutManagers.

Personally, I'm not a fan of this design at all (I found it very difficult to work with or do anything useful with Swing); but perhaps Swing is just a bad example and there are other ways in which the composite pattern could be useful and/or easy to work with?  I don't know on this one.


问:
Low coupling processing big quantities of data
Usually I achieve low coupling by creating classes that exchange lists, sets, and maps between them. Now I am developing a  Java batch application and I can't put all the data inside a data structure because there isn't enough memory. I have to read and process one chunk of data and then going to the next one. So having low coupling is much more difficult because I have to check somewhere if there is still data to read, etc.

What I am using now is:

Source -> Process -> Persist

The classes that process have to ask to the Source classes if there are more rows to read.

What are the best practices and or useful patterns in such situations?

I hope I am explaining myself, if not tell me.

答:
From the comments I see you're using Java. Have a look at various Queue implementations. Particularly, BlockingQueue is useful for producer-consumer scenarios. You could have two queues: one between Source (producer of data) and Process (consumer of data), and another between Process (producer of results) and Persist (consumer of results).

With limited-capacity blocking queues it's fairly easy to implement efficient (the bottleneck part, whatever it is, is kept fed with data 100% of the time) systems, still using only a bound amount of memory no matter how much data there is.


问:
Localization in php, best practice or approach?
I am Localizing my php application. I have a dilemma on choosing best method to accomplish the same.

Method 1: Currently am storing words to be localized in an array in a php file

```<code><?php

$values = array (
                        'welcome' => 'bienvenida'
                );

?>
</code>```

I am using a function to extract and return each word according to requirement

Method 2: Should I use a txt file that stores string of the same?

```<code><?php
$welcome = 'bienvenida';
?>
</code>```

My question is which is a better method, in terms of speed and effort to develop the same and why?

Edit: I would like to know which method out of two is faster in responding and why would that be? also, any improvement on the above code would be appreciated!!

答:
PHP has great built-in possibilities for localization. The most common way seems to be gettext - this tutorial shows how it's used.

Since PHP 5.3 there's also intl which offers a lot more features (to format numbers, dates and currencies depending on the locale for example).


问:
Group method parameter or individual parameter?
I would like to ask on method parameters design consideration. I am usually deciding between using individual variables as parameters versus grouping them to a class or dictionary as one parameter.

Is there such a rule when you should use individual parameter against using a class or a dictionary to group the parameter?

Individual parameter
- Straight forward, strongly typed

Dictionary parameter
- Very extensible, like HTTP request but cannot be strongly typed.

Class parameter
- Extensible by adding member to the class parameter, strongly typed.

I am looking for a design reference on when to use which?

Note: I am not sure if this question is valid in programmers but I definitely think it would be closed in stackoverflow, If it is still not valid, please point me to the proper page.

答: There is no clear rule to this, it depends on a lot of things. One rule of thumb is that if the method has more than 3-5 parameters, it is advisable to group them. My first approach in such a case would always be using parameter object(s). I would use a key-value map only as a last resort, when there is a huge and/or variable number of parameters whose types are not known at compile time.</p>


答:
Unix is not any more a single Operating System. It used to be an implementation by Bell Labs/ AT&T but now it is a standard.

Technically, Linux is only a kernel. This kernel can be found in non Unix like OSes, the most popular being Android. On the other hand, there are many Linux based OSes that are Unix like. Most (if not all) of them are using the Gnu libraries and utilities. This combination is providing Linux distributions the Unix API and compliance (or non compliance) to the standards.

The Unix standard doesn't require a compliant system to be proprietary or to have any particular license. BSDs, OpenSolaris/Illumos, darwin are examples of non Linux still free Unix implementations.

Compliant systems are usually but not always a mix of proprietary and open source components while Gnu/Linux can be either fully Open Source or also include proprietary stuff.

As far a Unix compliance is concerned, there are no much differences. Most Linux distributions and Unix implementations share the same set of commands using the same set of options. However, you will find a lot of extensions of the standard commands, especially on the Gnu side where they are called Gnuisms, and numerous commands that aren't defined by the standards in the first place (compilers, administrative commands, installation, packaging, graphic environment). This is an area where you can find a lot of divergence, incompatibilities and sometimes holy wars.

Gnu/Linux development model is usually considered to be more "organic" and "bazaar" like, while other Unix like systems are more "designed" and "cathedral" like. Depending on the subsystems, the difference is not that much clear-cut and depends the individuals and/or companies behind them.


答: My typical approach to this, like @peter-torok, is to group parameters if there is more than 3 (or some low value) with a class. I like to think that if it's more than this, then there's probably an important abstraction missing from your domain, in which case a class is justified.</p>

Title: Group method parameter or individual parameter?

Body:
I would like to ask on method parameters design consideration. I am usually deciding between using individual variables as parameters versus grouping them to a class or dictionary as one parameter.

Is there such a rule when you should use individual parameter against using a class or a dictionary to group the parameter?

Individual parameter
- Straight forward, strongly typed

Dictionary parameter
- Very extensible, like HTTP request but cannot be strongly typed.

Class parameter
- Extensible by adding member to the class parameter, strongly typed.

I am looking for a design reference on when to use which?

Note: I am not sure if this question is valid in programmers but I definitely think it would be closed in stackoverflow, If it is still not valid, please point me to the proper page.


答: Ask yourself which approach will give you code which is the most readable, and the easiest to maintain.  Code accordingly.</p>


问:
Does anyone prefer proportional fonts?
I was reading the wikipedia article on programming style and noticed something in an argument against vertically aligned code:

Reliance on mono-spaced font; tabular
  formatting assumes that the editor
  uses a fixed-width font. Most modern
  code editors support proportional
  fonts, and the programmer may prefer
  to use a proportional font for
  readability.

To be honest, I don't think I've ever met a programmer who preferred a proportional font.  Nor can I think of any really good reasons for using them.  Why would someone prefer a proportional font?

答:
I spent some time finding a good, readable font for Eclipse a while back, and under XP I used Verdana for quite some time.  Consolas settled that because it is truly superb for programming.

These are my findings:

Most proportional fonts are designed for prose and only little punctuation (which in turn is usually one or rarely two characters).  The C family of languages have lots of punctuation, which simply does not - in my opinion - look good and is harder to read than necessary.

Variable length characters mean that the length of lines vary.  This makes it close to impossible to guess where the cursor will end when navigating using arrow buttons.  I found this annoying.

Vertical spacing matters too.  This is normally not something that can be overridden easily, and most proportional fonts have less room between the lines than I'd like.

Very few IDE's are tested with proportional fonts.  This makes room for subtle bugs like putting the cursor in the wrong location, incorrectly repainting characters, and the like.

Hence I found that it was not worth the trouble for me.

Note on alignment and other layouts:  I have set Eclipse to auto-format each file on every save, so all fancy layouts are automatically reset.  Eclipse uses tabs instead of multiple spaces and these can be positioned correctly even with proportional fonts.  Hence formatter layouts can be over one another, but we use the standard formatter configuration which does not have that.

I believe that the enforcement of automatic formatting for everyone on every save minimizes the false positives in the source control system, when doing forensic analysis.

ContentLicense: CC BY-SA 2.5

Title: Does anyone prefer proportional fonts?


问:
WinRT for 'desktop' apps
So I'm reading up about the differences between the old and the new APIs, and I can't find whether the new WinRT API will provide for desktop apps, so far it seems its only available to write Metro apps - ie the full screen, 'phone style' apps.

Does this mean that I can write a WinRT-based app and it will be invoked from a desktop but display like other Metro apps (eg IE) and I won't be able to write an old-style desktop app that runs in the old-style desktop?

What does this mean for server side apps? I imagine WinRT would be the API of choice for servers, now that Windows Server comes with an optional GUI, so I imagine that if I can write a windows-less app using WinRT for the server, I should be able to write the same for the client too? (and if that's the case, surely I could connect a non-Metro UI to it)

答:
Microsoft is saying that you can, but that there's no documentation on it yet:

http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/e65f53b4-cac9-44e3-aa10-cd7955d6a9b3

We have received a number of inquiries in this area. The documentation will be expanding as the Windows 8 project progresses to include more API specific details.

It is possible to use WinRT from Desktop applications. WinRT APIs may be tied to Metro style apps, Desktop apps or potentially available to both. The documentation will list which environments (Desktop, Metro style or both) a given API works in.

Note: Custom WinRT components are only supported in Metro style applications. They are not supported in Desktop applications.

I don't know why they'd leave us in the dark for two public releases on something this important. Then again, Microsoft's inability to communicate lately has been bordering on pathological...

Title: WinRT for 'desktop' apps


答:
I once read that Linux is what you get when you take a PC developer and ask him to write a Unix OS, whereas FreeBSD is what you get when you take a Unix developer and ask him to make a PC OS.... don't forget the BSDs in your comparison!

The differences is mainly in the Kernel as the userspace applications (including things like ls) are all part of the GNU project. This means that Unix, FreeBSD, and Linux all appear to be pretty much the same thing.

However there are differences once you look closely. The directory layout will be different (but many Linux distros use their own mostly compatible but still different layouts anyway), the filesystems are different (Unix uses UFS, FreeBSD uses FFS, Linux uses Ext3 to be simplistic - all of them can use ports of common FSs, eg ZFS)

Then there are differences in core APIs, Linux will give you the inotify API to tell you when files changes, Mac OSX gives you FSEvents, and FreeBSD gives you kqueue.

So they can be considered the same family - compare a Windows system with GNU tools ported to it with a Linux system with the same tools. They will only superficially appear the same, but a Unix or FreeBSD system will still appear comparable. At a closer look, you'll find porting apps between FreeBSD, Unix and Linux relatively  easy compared to porting to alternative OSs such as Windows.


答:
Chapter 3 of the Clean Code book has a section in it about functions. It mentions that the ideal number of arguments is Zero, then next to ideal is One. Two if you really have to. Three should be avoided, and anything further should require special justification. This may seem similar to the answers given by both rupjones and Péter Török, however there is more to this than simply picking an arbitrary number of method parameters to deal with.

As David Wallace mentions in his answer, Readability and Maintenance are your key considerations. Every parameter you add to a method increases it's level of relative difficulty in terms of the reader's ability to understand what is going on in the method. So while a new class may be justified, the number of parameters should not be the defining reason for this. Every class you create is a new file and entity to maintain, and while this can often be the better option if it helps to keep your code clean and easy to reuse and change, this needs to be balanced against the complexity of the method and its usage of the class itself.

There are also other considerations. Your classes should only be responsible for one conceptual thing. If your method parameters are only loosely related, a class might not be justified. Your parameter list may even seem to suggest that you might need two classes, or a composite, or some other combination.

As with classes, you should also consider that your methods should only do one thing. If you have a lot of method arguments, or even if you use a large number of parameters on a class, then perhaps you're trying to do too many individual things within in a single method. You may be able to break your method down into a set of smaller methods, and in doing so reduce the clutter of parameters, and reduce the complexity of your method(s).

Waiting for your parameter list to grow before refactoring can often mean you've left a problem to be dealt with later on. It's often better to address such concerns as soon as they appear, to save you needing to deal with potentially difficult refactorings later on. Of course, if you have good test coverage, then this shouldn't be too difficult, however this should not mean you should allow yourself to become too complacent about addressing potential problems in your code as they become known to you.

So sure, there are no real hard or fast rules about this, however you'll find if you keep your methods small, and then try and find a way to make them smaller and without repetition, that many of these issues to do with the number of parameters or classes - while  no less relevant - will likely appear less often.


问:
On improving commit practices
I was thinking about ways to improving my commit practices.

Is there any co-relation between no. of source code lines and no. of commits?

In a recent project that I was involved in, I was going at 30 commits per 1000 lines.

One typical file from the project has these stats

```<code>language: JavaScript
total commits that include this file: 32

total lines: 1408
source lines: 1140
comment lines: 98

no. of function declarations: 28
other declarations: 8
</code>```

Another file has these...

```<code>Language: Python
total commits that include this file: 17

total lines: 933
source lines: 730
comment lines: 80

classes: 1
methods: 10
</code>```

I also think that no. of commits is more related to no. of features or no. of changes to the code and less to the no. of lines.

The general git community motto is make short commits and commit often.

So, do you really think about you commit strategy before you start the project. For that matter, is there anything like commit strategy? If so, what's yours?

答:
I don't think number of commits should be related to lines number. More likely to problems solved/features introduced. I use this rather simple approach (git):

Commit often to local branch, but only when something relevant changes (solved puzzling issue, added few important files/functions). This way, you can navigate easily between steps that took you to final solution of what you were working at given time.

Merge local commits into single feature/problem related commit when sending to remote/public repository. This way, whatever you did that goes public, is well described and coherent, so that everybody knows what you were doing (or at least has brief idea).

Overall, whatever you do locally is for you - stick to approach that works for you. Public commits should be more thought through, but I wouldn't develop whole new strategy if team already has working approach. Stay consistent with others.

Title: On improving commit practices


答:
If you're using a DVCS, you should be committing very often. I commit every time my code is in a stable state, which is not related to lines of code. You want a tree of lots of small, atomic commits that makes it easy to see what you did in each. If you're trying to track down a regression you found when testing, this makes it far easier to do a binary search and track down the exact commit, because you will have fewer changes per commit. I only commit when my code compiles - my idea of "atomic" is that it compiles, passes the regression unit tests, and passes a quick integration test. Sometimes a unit test is included, and sometimes not.

When you push, you should push whole features. The rest of the world doesn't want to see your "missed checking in this file" commits every day. Git provides rebase, which allows you to clean up your commit tree by squashing multiple commits together. The community seems to be uncertain about how much history you should commit. I'd say you should squash together the commits that don't show any of the history, like "missed file" or "dumb regression". You want to present as clean a history as you can so everyone can easily see what you did.

In a centralized version control system, you need to commit a lot more if you want to keep a good history. My recommendation is that you work on smaller features and complete them as much as you can before you commit. Your concept of "atomic" here should be a feature that works and is tested. You don't want to commit anything that break other developer's workspaces, because they will be updating often and it's a lot harder to work on independent features that overlap. You'll commit less, but those commits will usually be more meaty than your average DVCS.

You can see that the ratio of lines of code to number of commits depends on how big your features are and the workflow you use. Your workflow will be different depending on what version control system you use, so you can't generally predict what your commits will look like. Each institution has their own standard, and should determine for themselves what their workflow should ideally be.

Title: On improving commit practices

Body:
I was thinking about ways to improving my commit practices.

Is there any co-relation between no. of source code lines and no. of commits?

In a recent project that I was involved in, I was going at 30 commits per 1000 lines.

One typical file from the project has these stats

```<code>language: JavaScript
total commits that include this file: 32

total lines: 1408
source lines: 1140
comment lines: 98

no. of function declarations: 28
other declarations: 8
</code>```

Another file has these...

```<code>Language: Python
total commits that include this file: 17

total lines: 933
source lines: 730
comment lines: 80

classes: 1
methods: 10
</code>```

I also think that no. of commits is more related to no. of features or no. of changes to the code and less to the no. of lines.

The general git community motto is make short commits and commit often.

So, do you really think about you commit strategy before you start the project. For that matter, is there anything like commit strategy? If so, what's yours?


答: While I do feel that proportional fonts are prettier, in some of them, especially sans-serif fonts, its impossible to see the difference between an "I" and an "l". Wait, what did I name that variable again? </p>

Title: Does anyone prefer proportional fonts?

Body:
I was reading the wikipedia article on programming style and noticed something in an argument against vertically aligned code:

Reliance on mono-spaced font; tabular
  formatting assumes that the editor
  uses a fixed-width font. Most modern
  code editors support proportional
  fonts, and the programmer may prefer
  to use a proportional font for
  readability.

To be honest, I don't think I've ever met a programmer who preferred a proportional font.  Nor can I think of any really good reasons for using them.  Why would someone prefer a proportional font?


问:
Is using nested try-catch blocks an anti-pattern?
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```

答:
I solved this situation like this (try-catch with fallback):</p>

```<code>$variableForWhichINeedFallback = null;
$fallbackOptions = array('Option1', 'Option2', 'Option3');
while (!$variableForWhichINeedFallback && $fallbackOptions){
    $fallbackOption = array_pop($fallbackOptions);
    try{
        $variableForWhichINeedFallback = doSomethingExceptionalWith($fallbackOption);
    }
    catch{
        continue;
    }
}
if (!$variableForWhichINeedFallback)
    raise new ExceptionalException();
</code>```

Body:
I solved this situation like this (try-catch with fallback):

$variableForWhichINeedFallback = null;
$fallbackOptions = array('Option1', 'Option2', 'Option3');
while (!$variableForWhichINeedFallback && $fallbackOptions){
    $fallbackOption = array_pop($fallbackOptions);
    try{
        $variableForWhichINeedFallback = doSomethingExceptionalWith($fallbackOption);
    }
    catch{
        continue;
    }
}
if (!$variableForWhichINeedFallback)
    raise new ExceptionalException();


问:
What are deferred callbacks?
I understand the idea of a callback, where I pass a function into another function and that function then uses the supplied function at will.

I am struggling to understand deferred callbacks, even after googling it.

Could someone provide a simple explanation please? I program in Ruby, but also know C/C++ a bit, but most of all I was a experienced assembly language programmer. So I am wondering is it a bit like a stack of callback addresses that get pop'd? I am hoping to learn jquery or node.js and these deferred callbacks seem integral to both. I understand basic threading principles (though mutex object makes my head hurt ;)

答:
I am not sure but I believe a deffered callback refers to an asynchronous callback, so you'll have better luck googleing for that.

The best explanation I found was at http://www.nodebeginner.org

Hey, probablyExpensiveFunction(), please do your stuff, but I, the single Node.js thread, am not going to wait right here until you are finished, I will continue to execute the lines of code below you, so would you please take this callbackFunction() here and call it when you are finished doing your expensive stuff? Thanks!"

In this example, probablyExpensiveFunction is a non-blocking (or async function). This means that it's not executed right away, but placed in a so called event loop. The node.js thread will continue execution, but at some point in time, it will decide to execute something from the event loop. When it reaches probablyExpensiveFunction, it calls it, and when probablyExpensiveFunction  finishes execution, it calls the (deferred) callback passed as as a parameter to it.

As an example of probablyExpensiveFunction you can take fs.readFile

OwnerDisplayName: tentimes

Title: What are deferred callbacks?

OwnerDisplayName: mihai


答:
JavaScript is single-threaded, so you can't think in terms of threads to understand this. Here is an example of both regular and asynchronous callbacks using jQuery:</p>

```<code>var regularCallback = function(evt) {
    alert("I'm a callback!")
}
var asyncCallback = function(data) {
    alert("I only run when an async operation finishes!")
}

// Bind the regular callback to a button's click event
$('#mybutton').on('click', regularCallback);

// Start an ajax request to the server. The request is asynchronous, so code
// below this line will execute immediately. The callback function
// will only be called when the request is complete.
$.get("http://google.com", asyncCallback);
</code>```

Title: What are deferred callbacks?

Body:
I understand the idea of a callback, where I pass a function into another function and that function then uses the supplied function at will.

I am struggling to understand deferred callbacks, even after googling it.

Could someone provide a simple explanation please? I program in Ruby, but also know C/C++ a bit, but most of all I was a experienced assembly language programmer. So I am wondering is it a bit like a stack of callback addresses that get pop'd? I am hoping to learn jquery or node.js and these deferred callbacks seem integral to both. I understand basic threading principles (though mutex object makes my head hurt ;)

Body:
JavaScript is single-threaded, so you can't think in terms of threads to understand this. Here is an example of both regular and asynchronous callbacks using jQuery:

var regularCallback = function(evt) {
    alert("I'm a callback!")
}
var asyncCallback = function(data) {
    alert("I only run when an async operation finishes!")
}

// Bind the regular callback to a button's click event
$('#mybutton').on('click', regularCallback);

// Start an ajax request to the server. The request is asynchronous, so code
// below this line will execute immediately. The callback function
// will only be called when the request is complete.
$.get("http://google.com", asyncCallback);

OwnerDisplayName: bfavaretto


答:
The way a deferred callback works is each time you add a callback to it, that callback is pushed to an array. Then, when the .resolve() or .resolveWith() method is called on the deferred object, all .done() callbacks in the array are executed in order.

Now we can look at what a Deferred Object is. Take the snippet below as an example.

```<code>var deferred = $.Deferred();
var promise = deferred.promise();
</code>```

What we have now is a deferred object, and the deferred object's promise object. The Deferred object has all the same methods as the promise object, however the promise object only has the methods .done(), .fail(), and .always() which are used to add callbacks to the deferred object for each respective event. The deferred object on the other hand has several other methods, most importantly .resolve() and .reject(). When these methods are called on the deferred object, all callbacks are called. .resolve() fires the .done() and .always() callbacks while the .reject() method calls .fail() and .always() callbacks.

Generally the deferred object is kept hidden within a private scope, and the promise object is returned from the function so that callbacks can be placed on it. The deferred object will be resolved later, such as after an ajax request is complete or after an image is loaded, after a setTimeout, etc. It is also important to realize that a deferred object can only be resolved once. If it is already resolved, it's callbacks will be called immediately.

Here's another example, one that I use:

```<code>function loadImage(url) {
    var def = $.Deferred(),
        img = new Image();
    $(img).on("load error",function(e){
        if (e.type === "error") {
            def.reject(url);
        }
        else {
            def.resolve(url);
        }
    });
    img.src = url;
    // return the promise object so that callbacks can
    // be defined on the deferred object.
    return def.promise();
}
loadImage("foobar.jpg").done(function(){
    alert("The image is loaded!");
}).fail(function(){
    alert("The image failed to load!");
}).always(function(){
    alert("This is always called!");
});
</code>```

For more information on jQuery's $.Deferred() method and deferred objects, visit http://api.jquery.com/category/deferred-object/

Title: What are deferred callbacks?

Body:
The way a deferred callback works is each time you add a callback to it, that callback is pushed to an array. Then, when the .resolve() or .resolveWith() method is called on the deferred object, all .done() callbacks in the array are executed in order.

Now we can look at what a Deferred Object is. Take the snippet below as an example.

var deferred = $.Deferred();
var promise = deferred.promise();

What we have now is a deferred object, and the deferred object's promise object. The Deferred object has all the same methods as the promise object, however the promise object only has the methods .done(), .fail(), and .always() which are used to add callbacks to the deferred object for each respective event. The deferred object on the other hand has several other methods, most importantly .resolve() and .reject(). When these methods are called on the deferred object, all callbacks are called. .resolve() fires the .done() and .always() callbacks while the .reject() method calls .fail() and .always() callbacks.

Generally the deferred object is kept hidden within a private scope, and the promise object is returned from the function so that callbacks can be placed on it. The deferred object will be resolved later, such as after an ajax request is complete or after an image is loaded, after a setTimeout, etc. It is also important to realize that a deferred object can only be resolved once. If it is already resolved, it's callbacks will be called immediately.

Here's another example, one that I use:

function loadImage(url) {
    var def = $.Deferred(),
        img = new Image();
    $(img).on("load error",function(e){
        if (e.type === "error") {
            def.reject(url);
        }
        else {
            def.resolve(url);
        }
    });
    img.src = url;
    // return the promise object so that callbacks can
    // be defined on the deferred object.
    return def.promise();
}
loadImage("foobar.jpg").done(function(){
    alert("The image is loaded!");
}).fail(function(){
    alert("The image failed to load!");
}).always(function(){
    alert("This is always called!");
});

For more information on jQuery's $.Deferred() method and deferred objects, visit http://api.jquery.com/category/deferred-object/

OwnerDisplayName: Kevin B


答:
Deferred callbacks (aka Promices) allow you to write sequential asynchronous code, without pain and callback spaghetti:

```<code>$.when( doAjax(), doAnotherAjax() ).then( haveFunWithMoreAjax ).then( animateStuff );
</code>```

'when' lets you wait for functions to return in parallel, and then can be sequentially chained.

one note: jQuery deferreds != Promices/A, their syntax is a bit different.

There are good articles on topic: one at IEBlog and other in some random blog, a book and a popular stackoverflow question

Title: What are deferred callbacks?

Body:
Deferred callbacks (aka Promices) allow you to write sequential asynchronous code, without pain and callback spaghetti:

$.when( doAjax(), doAnotherAjax() ).then( haveFunWithMoreAjax ).then( animateStuff );

'when' lets you wait for functions to return in parallel, and then can be sequentially chained.

one note: jQuery deferreds != Promices/A, their syntax is a bit different.

There are good articles on topic: one at IEBlog and other in some random blog, a book and a popular stackoverflow question

ContentLicense: CC BY-SA 4.0


答: I've had commits for bug fixes that changed one character.  Size isn't really the determining factor here.  A good rule of thumb is to commit whenever you can think of a commit message that makes sense.  When to share your commits is a different question.  It varies by your group's culture, but generally involves you being reasonably confident your changes work as intended.

Title: On improving commit practices


问:
What are the best practices for phasing out obsolete code?
I have the need to phase out an obsolete method.  I am aware of the [Obsolete] attribute.  Does Microsoft have a recommended best practice guide for doing this?

Here's my current plan:

A.  I do not want to create a new assembly because developers would have to add a new reference to their projects and I expect to get a lot of grief from my boss and co-workers if they must do this.  We also do not maintain multiple assembly versions.  We only use the latest version.  Changing this practice would require changing our deployment process which is a big issue (have to teach people how to do things with TFS instead of FinalBuilder and get them to give up FinalBuilder)

B.  Mark the old method obsolete.

C.  Because the implementation is changing (not the method signature), I need to rename the method rather than create an overload.  So, to make users aware of the proper method I plan to add a message to the [Obsolete] attribute. This part bothers me, because the only change I'm making is decoupling the method from the connection string.  But, because I'm not adding a new assembly, I see no way around this.

Result:

```<code>[Obsolete("Please don't use this anymore because it does not implement IMyDbProvider.  Use XXX instead.")];
        /// <summary>
        ///
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        public static Dictionary<string, Setting> ReadSettings(string settingName)
        {
            return ReadSettings(settingName, SomeGeneralClass.ConnectionString);
        }

        public Dictionary<string, Setting> ReadSettings2(string settingName)
        {
            return ReadSettings(settingName);// IMyDbProvider.ConnectionString private member added to class.  Probably have to make this an instance method.
        }
</code>```

答:
Because the implementation is changing (not the method signature), I need to rename the method rather than create an overload.

I don't understand.  If the implementation is changing but the signature isn't, why would you ever do this?  Let the "old" method use the new and improved implementation.  Any developers consuming this API will be rolling their eyes when they see a method with the exact same signature created and deprecation warnings on their existing method calls. (Can you think of a time this has ever happened in an API?)

If you're unsure if changing the underlying implementation of this method will work, verify behavior with unit tests before and after you change the implementation.


答:
Microsoft uses the [obsolete] attribute to tell developers that the method, property or class is deprecated, and may be changed (or not supported at all) in future releases.

That gives you at least one release cycle to notify users of your API that their feature is "going away," and to remove references to it in future releases of their software.

How long you leave the original feature in is entirely up to you.  If you want to "strongly encourage" developers to use your new features over the old ones, you only need one additional release cycle to remove it.  If you intend to have permanent backwards compatibility, you can leave it in forever.

As Brian points out, if you're only changing the underlying implementation, but not the method signature, you may not need to do any of this at all.

Title: What are the best practices for phasing out obsolete code?

Body:
I have the need to phase out an obsolete method.  I am aware of the [Obsolete] attribute.  Does Microsoft have a recommended best practice guide for doing this?

Here's my current plan:

A.  I do not want to create a new assembly because developers would have to add a new reference to their projects and I expect to get a lot of grief from my boss and co-workers if they must do this.  We also do not maintain multiple assembly versions.  We only use the latest version.  Changing this practice would require changing our deployment process which is a big issue (have to teach people how to do things with TFS instead of FinalBuilder and get them to give up FinalBuilder)

B.  Mark the old method obsolete.

C.  Because the implementation is changing (not the method signature), I need to rename the method rather than create an overload.  So, to make users aware of the proper method I plan to add a message to the [Obsolete] attribute. This part bothers me, because the only change I'm making is decoupling the method from the connection string.  But, because I'm not adding a new assembly, I see no way around this.

Result:

```<code>[Obsolete("Please don't use this anymore because it does not implement IMyDbProvider.  Use XXX instead.")];
        /// <summary>
        ///
        /// </summary>
        /// <param name="settingName"></param>
        /// <returns></returns>
        public static Dictionary<string, Setting> ReadSettings(string settingName)
        {
            return ReadSettings(settingName, SomeGeneralClass.ConnectionString);
        }

        public Dictionary<string, Setting> ReadSettings2(string settingName)
        {
            return ReadSettings(settingName);// IMyDbProvider.ConnectionString private member added to class.  Probably have to make this an instance method.
        }
</code>```


答:
A blocking queue (from Joonas Pulakka) is the heavy-duty answer.  A simpler answer might work.  If you have all the data stored in the source, you can just pass a reference to the processor, and it can just grab the data out of the source.  Of course, this is probably what you were doing in the past.  You may not have all the data in memory in the source and you may not get the low coupling you want.

The next step up would be to use an Enumerator or Iterator interface.  (Iterators are more common in Java, though most times that remove method is just a nusance.)  The processor would obtain the Iterator from the source, then call the methods until done.  If the source is pulling terrabytes of data from somewhere, each call might take a while.  But if you're going to sleep the processor until there's something in the queue anyway, this will just be doing that automatically.  And if the source gets ahead of the producer, the source will automatically wait for the producer to call hasNext and next.

If, on the other hand, you want the source grabbing data from its source as fast as it can and stockpiling it until the processor catches up, not sitting around waiting for the processor to process, then the queue--and multiple threads--start to look like a good, if more complicated, idea.  Now the source can pile up the data when it can run faster (its limit presumably being something like disk I/O), and the processor can reduce the size of the pile when it can run faster, (its limit being how fast the persistance module can persist the data).

Title: Low coupling processing big quantities of data

Body:
Usually I achieve low coupling by creating classes that exchange lists, sets, and maps between them. Now I am developing a  Java batch application and I can't put all the data inside a data structure because there isn't enough memory. I have to read and process one chunk of data and then going to the next one. So having low coupling is much more difficult because I have to check somewhere if there is still data to read, etc.

What I am using now is:

Source -> Process -> Persist

The classes that process have to ask to the Source classes if there are more rows to read.

What are the best practices and or useful patterns in such situations?

I hope I am explaining myself, if not tell me.


问:
Should I add old code into my repository?
I've got an SVN repository of a PHP site and the last programmer didn't use source control properly. As a result, only code since I started working here is in the Repo.

I have a bunch of old copies of the full code base saved in files as "backups" but they're not in source control. I don't know why most of the copies were saved nor do I have any reasonable way to tag them to a version number. I do have the dates the backups were made, all backups have proper file system timestamps.

Due to upgrades to the frameworks and database drivers involved, the old code is quite defunct; it no longer works on the current server configuration. However, the previous programmers had some unique logic, so I hate to be completely without old copies to refer to what on earth they were doing.

Should I keep this stuff in version control? How? Wall off the old code in separate Tags/branches?

答:
I personally would.  You do need to make sure that you keep them all separate, probably like you said, wall it off with tags.  You might be able to use the date the file was last edited to figure out a general order of things.

Putting it in SVN would about be good to kind of show the history.  It sounds like you'll need it, if they have some odd snippets seeing the file's history would be useful.  Not to mention you have the entire (known) history of the project in one place.  Can't really think of a reason not to, although I could be missing something important.


答: I would use a separate dir, something like "legacy" to have all the necessary Stuff in one Place.</p>

Title: Should I add old code into my repository?

Body:
I've got an SVN repository of a PHP site and the last programmer didn't use source control properly. As a result, only code since I started working here is in the Repo.

I have a bunch of old copies of the full code base saved in files as "backups" but they're not in source control. I don't know why most of the copies were saved nor do I have any reasonable way to tag them to a version number. I do have the dates the backups were made, all backups have proper file system timestamps.

Due to upgrades to the frameworks and database drivers involved, the old code is quite defunct; it no longer works on the current server configuration. However, the previous programmers had some unique logic, so I hate to be completely without old copies to refer to what on earth they were doing.

Should I keep this stuff in version control? How? Wall off the old code in separate Tags/branches?


答:
According to Code Complete, this depends on the conceptual abstraction layer you're programming at. Software's primary technical imperative is managing complexity, so make sure you're not mixing abstractions.

For example,

```<code>public class Vechicle {
    private int id;
    private Door door;
    private Window window;
    private Trunk trunk;

    public void addDoorAndWindow(Door door, Window window) {
      // passing a vechicle object is inappropriate here,
      // you shouldn't access the parameters with vechicle.getDoor() or vechicle.getWindow()
    }

    public void collide(Vechicle vechicle) {
      // passing the id is inappropriate is here
      // if you need it, get it with vechicle.getId()
    }
}
</code>```

You ask the question, does it make sense to pass a Vechicle to and addDoorAndWindow method. No, you're adding door and window, and not a vechicle. Does it make sense to pass an id to collide method. No, you're not collding with an id, you're colliding with a vehicle.

If you get too many individual parameters, and they are sort of related, then try introducing a Parameter Object.

Body:
According to Code Complete, this depends on the conceptual abstraction layer you're programming at. Software's primary technical imperative is managing complexity, so make sure you're not mixing abstractions.

For example,

public class Vechicle {
    private int id;
    private Door door;
    private Window window;
    private Trunk trunk;

    public void addDoorAndWindow(Door door, Window window) {
      // passing a vechicle object is inappropriate here,
      // you shouldn't access the parameters with vechicle.getDoor() or vechicle.getWindow()
    }

    public void collide(Vechicle vechicle) {
      // passing the id is inappropriate is here
      // if you need it, get it with vechicle.getId()
    }
}

You ask the question, does it make sense to pass a Vechicle to and addDoorAndWindow method. No, you're adding door and window, and not a vechicle. Does it make sense to pass an id to collide method. No, you're not collding with an id, you're colliding with a vehicle.

If you get too many individual parameters, and they are sort of related, then try introducing a Parameter Object.


答:
If you have reasonable timestamps on each of these working versions then perhaps you can check them in one at a time until you get to the most recent version of the codebase, your latest changes.

The problem with the Tag approach like everybody else suggests is that you will lose changeset history on each file and this will make comparisons between older versions of the code more difficult.


答: The existing answers already mention some of the differences that you are looking for. Without being the Linux kernel expert, I'd also add that many of the design/implementation differences between GNU/Linux and the various Unices are covered in the Linux kernel design patterns series.</p>


答:
I've "had" to do this in a test class coincidentially (JUnit), where the setUp() method had to create objects with invalid constructor parameters in a constructor that threw an exception.

If I had to make the construction of 3 invalid object fail, for example, I would need 3 try-catch blocks, nested. I created a new method instead, where the exceptions where caught, and the return value was a new instance of the class I was testing when it succeeded.

Of course, I only needed 1 method because I did the same 3 times. It might be not such a good solution for nested blocks that do totally different things, but at least your code would become more readable in most cases.

Title: Is using nested try-catch blocks an anti-pattern?

Body:
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```


问:
Checking preconditions or not
I've been wanting to find a solid answer to the question of whether or not to have runtime checks to validate input for the purposes of ensuring a client has stuck to their end of the agreement in design by contract. For example, consider a simple class constructor:

```<code>class Foo
{
public:
  Foo( BarHandle bar )
  {
    FooHandle handle = GetFooHandle( bar );
    if( handle == NULL ) {
      throw std::exception( "invalid FooHandle" );
    }
  }
};
</code>```

I would argue in this case that a user should not attempt to construct a Foo without a valid BarHandle. It doesn't seem right to verify that bar is valid inside of Foo's constructor. If I simply document that Foo's constructor requires a valid BarHandle, isn't that enough? Is this a proper way to enforce my precondition in design by contract?

So far, everything I've read has mixed opinions on this. It seems like 50% of people would say to verify that bar is valid, the other 50% would say that I shouldn't do it, for example consider a case where the user verifies their BarHandle is correct, but a second (and unnecessary) check is also being done inside of Foo's constructor.

答:
I don't think there is a single answer to this. I think the main thing that's necessary is consistency -- either you enforce all preconditions on a function, or else you don't try to enforce any of them. Unfortunately, that's fairly rare -- what typically happens is that instead of thinking about the preconditions and enforcing them, programmers add bits of code to enforce preconditions whose violation happened to cause failures during testing, but frequently leave other possibilities open that may cause failure but didn't happen to arise in testing.

In many cases, it's quite reasonable to provide two layers: one for "internal" use that makes no attempt at enforcing any preconditions, and then a second for "outside" use that just enforces preconditions, then invokes the first.

I do, however, think it's better to have the preconditions enforced in the source node, not just documented. An exception or assert is much harder to ignore than documentation and a lot more likely to stay synchronized with the rest of the code.

OwnerDisplayName: Robert Dailey

Title: Checking preconditions or not

OwnerDisplayName: Jerry Coffin


答:
It's a very difficult question, because there are several different concepts:

Correctness

Documentation

Performance

However this is mostly an artifact of a type fault, in this case. Nullity is better enforced by type constraints, because the compiler actually checks those. Still, because not everything can be captured in a type system, especially in C++, the question itself is still worth it.

Personally, I think that correctness and documentations are paramount. Being fast and wrong is useless. Being fast and only wrong sometimes is a bit better, but does not bring much to the table either.

Performance though may be critical in some parts of the programs, and some checks can be quite extensive (ie: prove that a directed graph has all its nodes both accessible and co-accessible). Therefore I would vote for a dual approach.

Principle one: Fail Fast. This is a guiding principle in defensive programming in general, which advocates detecting errors at the earliest stage possible. I would add Fail Hard to the equation.

```<code>if (not bar) { abort(); }
</code>```

Unfortunately, in a Production environment failing hard is not necessarily the best solution. In this case a specific exception can help getting out of there in a hurry, and let some high-level handler catch on and deal with the failed case appropriately (most likely logging and forging ahead with a new case).

This however does not address the issue of expensive tests. In hot spots, those tests may cost too much. In this case, it is reasonable to only enable the test in DEBUG builds.

This leaves us with a nice and simple solution:

SOFT_ASSERT(Cond_, Text_)

DEBUG_ASSERT(Cond_, Text_)

Where the two macros are defined thusly:

```<code> #ifdef NDEBUG
 #  define SOFT_ASSERT(Cond_, Text_)                                                \
        while (not (Cond_)) { throw Exception(Text_, __FILE__, __LINE__); }
 #  define DEBUG_ASSERT(Cond_, Text_) while(false) {}
 #else // NDEBUG
 #  define SOFT_ASSERT(Cond_, Text_)                                                \
        while (not (Cond_)) {                                                       \
            std::cerr << __FILE__ << '#' << __LINE__ << ": " << Text_ << std::endl; \
            abort();                                                                \
        }
 #  define DEBUG_ASSERT(Cond_, Text_) SOFT_ASSERT(Cond_, Text_)
 #endif // NDEBUG
</code>```

Title: Checking preconditions or not

Body:
I've been wanting to find a solid answer to the question of whether or not to have runtime checks to validate input for the purposes of ensuring a client has stuck to their end of the agreement in design by contract. For example, consider a simple class constructor:

```<code>class Foo
{
public:
  Foo( BarHandle bar )
  {
    FooHandle handle = GetFooHandle( bar );
    if( handle == NULL ) {
      throw std::exception( "invalid FooHandle" );
    }
  }
};
</code>```

I would argue in this case that a user should not attempt to construct a Foo without a valid BarHandle. It doesn't seem right to verify that bar is valid inside of Foo's constructor. If I simply document that Foo's constructor requires a valid BarHandle, isn't that enough? Is this a proper way to enforce my precondition in design by contract?

So far, everything I've read has mixed opinions on this. It seems like 50% of people would say to verify that bar is valid, the other 50% would say that I shouldn't do it, for example consider a case where the user verifies their BarHandle is correct, but a second (and unnecessary) check is also being done inside of Foo's constructor.

Body:
It's a very difficult question, because there are several different concepts:

Correctness

Documentation

Performance

However this is mostly an artifact of a type fault, in this case. Nullity is better enforced by type constraints, because the compiler actually checks those. Still, because not everything can be captured in a type system, especially in C++, the question itself is still worth it.

Personally, I think that correctness and documentations are paramount. Being fast and wrong is useless. Being fast and only wrong sometimes is a bit better, but does not bring much to the table either.

Performance though may be critical in some parts of the programs, and some checks can be quite extensive (ie: prove that a directed graph has all its nodes both accessible and co-accessible). Therefore I would vote for a dual approach.

Principle one: Fail Fast. This is a guiding principle in defensive programming in general, which advocates detecting errors at the earliest stage possible. I would add Fail Hard to the equation.

if (not bar) { abort(); }

Unfortunately, in a Production environment failing hard is not necessarily the best solution. In this case a specific exception can help getting out of there in a hurry, and let some high-level handler catch on and deal with the failed case appropriately (most likely logging and forging ahead with a new case).

This however does not address the issue of expensive tests. In hot spots, those tests may cost too much. In this case, it is reasonable to only enable the test in DEBUG builds.

This leaves us with a nice and simple solution:

SOFT_ASSERT(Cond_, Text_)

DEBUG_ASSERT(Cond_, Text_)

Where the two macros are defined thusly:

 #ifdef NDEBUG
 #  define SOFT_ASSERT(Cond_, Text_)                                                \
        while (not (Cond_)) { throw Exception(Text_, __FILE__, __LINE__); }
 #  define DEBUG_ASSERT(Cond_, Text_) while(false) {}
 #else // NDEBUG
 #  define SOFT_ASSERT(Cond_, Text_)                                                \
        while (not (Cond_)) {                                                       \
            std::cerr << __FILE__ << '#' << __LINE__ << ": " << Text_ << std::endl; \
            abort();                                                                \
        }
 #  define DEBUG_ASSERT(Cond_, Text_) SOFT_ASSERT(Cond_, Text_)
 #endif // NDEBUG


问:
What was the most used programming language before C was created?
C is a language written between '69 and '73 according to WIkipedia. I imagine it made programming a whole lot easier and opened the gate for other programming languages.

My question, however, is what programming language dominated the market before C appeared? I'm tempted to say fortran and/or BASIC but I wasn't even alive back then so I have no idea.

By "most used", I mean a MUST-LEARN programming language, which most programmers were using at the time.

答:
What about COBOL?

Still a MUST-LEARN in some businesses today.


答:
Pascal was the direct predecessor to C for a large number of purposes. C did "unify" things a bit though. Before C, you often had to choose between Pascal, assembly language, or FORTRAN based on the capabilities you needed. C largely (but not completely) replaced all three. You often wanted to use Pascal, but couldn't. You grudgingly chose FORTRAN for performance, or assembly language for low-level access.

FORTRAN still had (and has) better performance than C, and assembly language still has more low level access -- but for many purposes, what C provided was enough.

Edit: I suppose I should add (as alluded to by Keith Thompson) Pascal doesn't really predate the creation of C by enough to notice. Pascal did, however, become widely pervasive relatively quickly. In the late '70s and early '80s, most typical hackers were at least vaguely aware of the existence of C, but only a relatively small number really used it.

During the CP/M days, for example, I can recall having a choice of a half dozen (or so) Pascal compilers: Microsoft Pascal, Pascal/S, Pascal/MT+, JRT Pascal, etc. Only toward the very end of CP/M, and into the early use of the IBM PC did C compilers start to become an option -- and even then, you choices were extremely limited. The first two I remember were BDS C and Whitesmith's C. BDS seemed to work well, but was limited enough that most "real C" programs wouldn't port to it. Whitesmiths also had some idiosyncrasies, was so expensive most people couldn't afford it, and so large that you typically had to swap floppy disks a half dozen (or so) times to compile even the simplest piece of code. A non-toy program could easily take several minutes to build, requiring operator intervention the entire time. The other option of the time was Micro-C, which (as you can guess from the name) was stripped down to the point that it took quite a bit of work to port to it -- not to mention the fact that if you wanted to run it on CP/M, you have to get the source code from Dr. Dobbs (printed), typed into your system, and then port it to CP/M on your own.

By contrast, Turbo Pascal became available around 1981 or '2 (if memory serves). It compiled in-memory, so small programs could compile and start to execute essentially instantly, even on a 1 MHz processor. The earlier Pascal compilers weren't that fast, but still a lot more reasonable than any C compiler of the time.

At least for people outside universities, C only started to become a reasonable choice around the mid-1980's or so. Early on you have Mark Williams, Datalight, and so on -- lots of companies that are long gone now. Then Borland came out with Turbo C, Microsoft answered with Quick C, and programmers could (and did) debate endlessly about the relative merits of a dozen different compilers.

Title: What was the most used programming language before C was created?

Body:
C is a language written between '69 and '73 according to WIkipedia. I imagine it made programming a whole lot easier and opened the gate for other programming languages.

My question, however, is what programming language dominated the market before C appeared? I'm tempted to say fortran and/or BASIC but I wasn't even alive back then so I have no idea.

By "most used", I mean a MUST-LEARN programming language, which most programmers were using at the time.


答:
By request, here are comments presented as an answer:

I'm not sure you completely grok the fact that functions in JS are first-class objects, and can therefore be stored until needed, past the time they are created.

For example, say you want to write to a file, then print out a log message; so you call the "write()" function (or whatever) and pass it a function that outputs the log message (this is the deferred callback function). "write()" internally stores a reference to the given function, starts writing to the file, and sets up its own callback to know when the write is finished. It then returns before the write is done; when it is, the internal callback is somehow called (this is the underlying framework's job -- in the case of node.js, it's done with an event loop), which then calls your callback which prints the log message.

The "deferred" part simply means that your callback function isn't called right away; calling it is deferred until the appropriate time. In the case of asynchronous functions like many of those in node.js, the given callback is generally called when the operation completes (or an error occurs).

Most stuff is async in node.js, but in the browser with e.g. jQuery, most stuff is actually synchronous (except, obviously, for AJAX requests). Since first-class functions are so handy in JavaScript (especially because of great closure support), callbacks are used everywhere in the browser too, but they're not "deferred" for synchronous operations (except insofar as they're not called immediately by you, but later on by the function you call).

The fact that the underlying system is event-driven is orthogonal to the use of deferred callbacks; you can imagine a (very slow) version of node.js that started a thread for every operation, and then called your given callback when the thread finished its work, without using events at all. Of course, this is a horrible model, but it illustrates my point :-)

Title: What are deferred callbacks?


答: Pascal, Fortran, Assembly, and Algol were the most used languages before C. C sort of replaced all of them. For business applications, COBOL (eek!) was the standard.</p>


问:
How to set-up a simple subversion workflow
I am trying to set-up a simple SVN workflow at home. I am new to subversion (and programming) so I have been reading the official PDF documentations but still not sure about how to set-up my repository.

I am working mainly with python, bash and rsl (Renderman Shading Language)

So I already have a /dev structure on my disk as this:

http://imageshack.us/f/708/devstructure.png/

And I have a /site structure that links to my /dev folder:

http://imageshack.us/f/651/sitestructure.png/

So obviously starting to use SVN will change this approach that I already have in place.

The question is when I am setting-up my SVN repository for the work I do in my /dev folder:

Will I set-up a separate repository for each different programming platform?
and Where exactly I should be placing my repository?

Thanks.

答:
If you new to subversion I would suggestion skipping SVN and moving straight to Git (or Mercurial if you what).  Git (and other distributed version control systems) are designed to work a lot better locally and for the most part have everything you would need from something like subversion.

If you do go with git I would highly suggest you learn the command line and GUI tools can only do so much but if you want a good GUI tool (which I use generally for looking at the log/diffs) I would suggest:

Windows

Git Extensions

Mac

Source Tree (Free in the Mac App Store)

GitHubs Mac Client (http://mac.github.com)

Linux

I have yet to get one to work so you are on your own here


问:
How important is it for a programmer to have an online presence?
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?

答:
It entirely depends on where you want to work. There is no universal answer to this.

Many (all?) employers will google your name and look you up. You really should do that as well to see what comes back.

The best way to control what they see is to have your own presence - something that will push any results that you don't want them to see way down the list, where they won't click through.

However, having an online presence is different from having a presence that shows you are active in your programming community. Blogging, answering questions on forums or Stack Exchange sites, participating in open source (or starting such) projects, writing articles etc show that. All of these are bonuses as far as good employers are concerned.

None of the above are requirements for getting a job, but they are all good to have in order to increase your chances. In other words, given two candidates that score similarly on the points the employer cares about, if one shows participation in the community and the other doesn't, the one that does will have a better chance at getting the offer.


答:
I can't imagine and employer turning you down because you don't have a presence online, however I can see them turning you down if you have a negative presence online. Certainly participation on sites such as these can really make you look better when your employer looks you up, so it's not a bad idea to expose some of these types of sites online.

You can check out tools like WebMii to find out your internet presence. Employers often use tools like this on top of simple Google searches.

Title: How important is it for a programmer to have an online presence?

Body:
I've noticed more and more mentions (both in posts here and in actual job descriptions) of programmers' "portfolios" - typically their public profiles on sites such as this, GitHub, etc.

How important is this, and would companies (startups in particular) reject (or immediately discard without even interviewing) otherwise outstanding candidates who don't have an online presence?

Personally, I prefer to keep a very low profile online. My name here cannot identify me, and I have other handles for other sites. I have a very spartan (and completely private) Facebook page. I do code on my own, but the code lives in local repositories. In general, the less information online about me, the better.

I could see a designer needing some sort of online portfolio, but for a programmer, is this really a big negative when job-searching?


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Anytime I read the following:

//Don't put in negative numbers or it will crash the program.
```

Or something similar.  If that's the case then put in an assert!  Let the debugger know that during run-time you don't want those values and make sure the code spells out the contract with the caller.

Body:
Anytime I read the following:

//Don't put in negative numbers or it will crash the program.

Or something similar.  If that's the case then put in an assert!  Let the debugger know that during run-time you don't want those values and make sure the code spells out the contract with the caller.


答:
If a start-up immediately rejects you, an otherwise outstanding candidate, for lack of online presence, it would be a strong indication of questionable hiring practices of the owners of that start-up, and so you should be glad that they did not hire you.

I worked for three start-ups over the course of ten years, and every time a major part of deciding to join had to do with my trust of the owners. I would not trust an owner with demonstrably shallow approach to hiring, the most essential part of growing a start-up into a company of respectable size.


答:
Having a strong online presence surely helps a lot, but not a must.

As an applicant to a job, you need to show them a bit of what you are capable of to get an interview generally, assuming the firm has a large pool of applicants to choose from.

The review process really changes a lot depending on type of the firm, location and the open position. Some firms doesn't even bother to search online, and some will only do a small search. But, especially for popular firms and for good paying positions, here is what goes on generally:

They will post some ads for the open position, requiring you to fill out a form or asking for resume or requiring a solution to a problem they posted.

They will sift through the applications, eliminating some percent of them by looking at the answers or resume.

They will search the applicants that passed the first stage online, on Google and other social sites. They will check blogs, github, bitbucket, SE like sites, mailing lists, forums etc. to get to know you a little bit more, to see if you worth an interview. They will eliminate some of the applicant at this phase also.

At this stage, generally they will only have a small amount of applicants left, and they will start interviews.

Now, if you have a strong resume (work experience in related areas, good references etc.), the online search part may not matter much.

But, if you don't have much to write at your resume, your online profile becomes the main resource for the interviewer to learn about you. If you don't have much to show at that stage, and there are other applicants that have a resume like you but have a strong online presence to show them they are capable of doing good work, they will get bonus points.

The main point is, you need to get ahead of other applicants to get an interview, and having a strong online presence helps with that. It's not a must, but generally its a plus.


答:
I think this is tough to answer. For the jobs being posted and filled the old fashion way, you probably don't need this and I doubt anyone there would check to even see if you are online. The question is, how many jobs are being filled based on finding individuals online? Your online presece may help make connections that lead to a good job. This can be a great substitute for devs with little work experience.

We all want to be evaluated on our merits to do the job. Often we lose the "luck of the draw" because we only have 4 years instead of the required 5 (I know no one ever sticks to that.), or didn't go to the right school, or obtained a particular certification, show tatoos or don't, put on a suit and tie, didn't comment your FizzBuzz test or you lack communication skills have prevented someone from getting a job one time or another.

Some may feel that you won't fit into the team or corporate culture if you're not a blogger. A specific project may be a perfect match, but does that web service framework you built mean you know nothing about mobile apps or you won't like that type of project?

Like everything, if you do it right, it will pay-off in the long-run.


问:
MIT app executing a GPL command
Can my MIT/BSD licensed, open source project, or a closed source project I build and sell, execute a command, where the command is a program released under the GPL?

I would not be distributing any version of the GPL'd program, either source code or binary. I would be telling the customer/end user that they need to have the package/binary installed prior to running the program.

答:
I don't think there's a problem as long as you don't include GPL code in the same executable. Calling external tools in the command line doesn't necessarily break your license.

In practice, doing what you suggested allows the customer/end user to replace the existing command by some custom solution at any moment.

PS: I'm not a lawyer, so you should probably talk to one.

Title: MIT app executing a GPL command


问:
Why is a database represented as a cylinder in architecture drawings?
I'm a young upstart programmer and I've never actually seen a database. But computers in large part come in boxes, not in cylinders so I was wondering why they are always represented as a cylinder when people show their architecture drawings.

Is there a reason why or is it just tradition to draw them like that?

答: Because their main purpose is to write data to a cylinder (disk).</p>


答: Although I don't have a specific reference to cite, I took it to represent a hard drive.  Historically, hard drives store data magnetically on round cylinders.  Since databases are all about persistance, hard drives are the mechanism for doing so.</p>

Title: Why is a database represented as a cylinder in architecture drawings?

Body:
I'm a young upstart programmer and I've never actually seen a database. But computers in large part come in boxes, not in cylinders so I was wondering why they are always represented as a cylinder when people show their architecture drawings.

Is there a reason why or is it just tradition to draw them like that?


答: I've always looked at the icon more as a silo than a cylinder: that is, a large high-volume container that can store loads of grain/salt/data.</p>


问:
What is meant by a primitive data type?
My understanding of a primitive datatype is that

It is a datatype provided by a language implicitly (Others are user defined classes)

So different languages have different sets of datatypes which are considered primitive for that particular language. Is that right?

And what is the difference between a "basic datatype" and "built-in datatype". Wikipedia says a primitive datatype is either of the two.

PS - Why is "string" type considered as a primitive type in SNOBOL4 and not in Java ?

答:
For better understanding the concept of primitive types and user-defined datatypes all that the other answers lacks is the concept of compiler.

If you understand the concept of lexemes getting selected as tokens, you will come to know that primitives are the only datatypes that a compiler knows by itself.

Title: What is meant by a primitive data type?


答:
The icon is probably meant to represent an old-school disk pack like this

,

mainly because databases typically reside on a large random-access device like an HDD.


问:
How to deal with social login
In my new web app I'm going to allow social login through Twitter (maybe), Facebook and Google and I'm in search of the best way to do it.

Actually I'm using Rails with Devise + Omniauth and this is the problem:

Should I ask the user to choose a password so that he can login without a social network?

Or maybe the user should be able to set a password if he want (for example when editing his account?)

The second way seems the best one but since Twitter doesn't provide user email and google doesn't provide an username I'll probably have to ask the user for username/email when he log in so in that case I may also ask for the password...

waht do you think?

答:
If the application is public you may want to prefer single-sing-on approach. You should conceptually separate user profile information from the physical implementation. That is, you collect all the information the user can provide you and use the subset required to satisfy the logon requirements.

If your user decided that he/she does not want to select a social network, then you need to allow them the regular login with userid and password. I guess this site works this way.

Title: How to deal with social login


答:
The necessity of an online profile varies with what kind of work you are applying for. Freelancing web designers need a more robust online portfolio than a senior developer for embedded systems. Just keep in mind that some fields may be a bit more challenging to get in to without an online portfolio.

I too like the idea of trying to keep as minimalist as possible my self created online profile, companies are capable of getting enough information about me other ways without my help adding more. Just always make sure once in a while Googleing your name doesn't turn up anything too damning.


答:
Definately allow the user to add a password if they want so that they have the option to login without using a social network sign-in.  If, for no other reason, that you are not reliant on an external party and not dead-in-the-water if their servers are down (or, even, if their government shuts off access to them).

Unless your app is something that integrates with and requires a social network, I'd recommend still providing a way to sign-up directly, without a social network involved.  While social network authentication is convenient, a lot of people dont have google/facebook/twitter accounts (yes, its true), and others just arent big fans of the idea that they can be tracked in that manner.

Title: How to deal with social login

Body:
In my new web app I'm going to allow social login through Twitter (maybe), Facebook and Google and I'm in search of the best way to do it.

Actually I'm using Rails with Devise + Omniauth and this is the problem:

Should I ask the user to choose a password so that he can login without a social network?

Or maybe the user should be able to set a password if he want (for example when editing his account?)

The second way seems the best one but since Twitter doesn't provide user email and google doesn't provide an username I'll probably have to ask the user for username/email when he log in so in that case I may also ask for the password...

waht do you think?


答:
I fully agree with Oded, lack of online presence might hurt when looking for new position but keep in mind that developers usually dont have online presence or keep it under wraps just like you so at this moment this might not be such an issue at all.

Since you are already present online, probably the best solution would be to add links for your online profiles into CV so those employers can get info about you but others cant.


问:
Best solution for getting referral information in PHP
I am currently redoing some link structuring on a website. In the past we have used specific php files on the last step to direct the user to the proper place.

Example:

```<code>www.example.com/action/go-to-blue.php
</code>```

or

```<code>www.example.com/action/short/go-to-red.php

www.example.com/action/tall/go-to-red.php
</code>```

We are now restructuring to eliminate the /short/ or /tall/ directory. What this means is now go-to-blue.php will be doing some extra processing to make sure it sends the visitor to the proper place.

The static method of the past was quite effective, because, well, if they left from that page we knew we had it right. Now since we are 301 redirecting action/short/go-to-red.php
to just action/go-to-red.php it is quite important on go-to-red.php that we realize a user may have been redirected from /short/ or /tall/.

So right now I am using HTTP_REFERRER and of course in my testing that works fine, but after a lot of reading it is clear that this is not a solid solution, so I was starting to brainstorm on other ways to check and make sure we get the proper referral information.

If we could check HTTP_REFERRER plus some other test, I would feel confident we have a pretty good system in place to send the visitor to the right place.

Some questions/comments:

Could I use a session variable or a cookie to accomplish this goal?

If so, would that be maintained through the 301 redirect? I don't see why it wouldn't be..

Passing the url in the url is not an option in this case.

答: If you user has cookies enabled writting into session will work but still there can be problems with users not having cookies enabled (only a small fraction of all users but still can cause problems if looking for a bullet proof solution)</p>


答:
Yes. If your program does not contain any code - source or object - from a GPL'd work, then it is not subject to the GPL.

I am not a lawyer, nor do i retain any, but Oracle does. Lots of them, rather (in)famously. Oracle distributes version of many of its products that run on Linux. The Linux kernel and most of its utilities are GPL'd, and its products certainly call them. If Oracle's lawyers think that's okay, then i think it's more than likely that it's okay.

Title: MIT app executing a GPL command

Body:
Can my MIT/BSD licensed, open source project, or a closed source project I build and sell, execute a command, where the command is a program released under the GPL?

I would not be distributing any version of the GPL'd program, either source code or binary. I would be telling the customer/end user that they need to have the package/binary installed prior to running the program.


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
when phpmyadmin asked:

"You are about to DESTROY a complete database! Do you really want to DROP DATABASE xxx?"

I hit Enter.

Title: Biggest mistake you've ever made


答:
It's okay. A refactoring to consider is pushing the code into its own method, and using early exits for success, letting you write the different attempts to do something at the same level:

```<code>try {
    // do something
    return;
} catch (Exception e) {
    // fall through; you probably want to log this
}
try {
    // do something in the same line, but being less ambitious
    return;
} catch (Exception e) {
    // fall through again; you probably want to log this too
}
try {
    // Do the minimum acceptable
    return;
} catch (Exception e) {
    // if you don't have any more fallbacks, then throw an exception here
}
//More try catches?
</code>```

Once you have it broken out like that, you could think about wrapping it up in a Strategy pattern.

```<code>interface DoSomethingStrategy {
    public void doSomething() throws Exception;
}

class NormalStrategy implements DoSomethingStrategy {
    public void doSomething() throws Exception {
        // do something
    }
}

class FirstFallbackStrategy implements DoSomethingStrategy {
    public void doSomething() throws Exception {
        // do something in the same line, but being less ambitious
    }
}

class TrySeveralThingsStrategy implements DoSomethingStrategy {
    private DoSomethingStrategy[] strategies = {new NormalStrategy(), new FirstFallbackStrategy()};
    public void doSomething() throws Exception {
        for (DoSomethingStrategy strategy: strategies) {
            try {
                strategy.doSomething();
                return;
            }
            catch (Exception e) {
                // log and continue
            }
        }
        throw new Exception("all strategies failed");
    }
}
</code>```

Then just use the TrySeveralThingsStrategy, which is a kind of composite strategy (two patterns for the price of one!).

One huge caveat: don't do this unless your strategies are themselves sufficiently complex, or you want to be able to use them in flexible ways. Otherwise, you're larding a few line of simple code with a huge pile of unnecessary object-orientation.

Body:
It's okay. A refactoring to consider is pushing the code into its own method, and using early exits for success, letting you write the different attempts to do something at the same level:

try {
    // do something
    return;
} catch (Exception e) {
    // fall through; you probably want to log this
}
try {
    // do something in the same line, but being less ambitious
    return;
} catch (Exception e) {
    // fall through again; you probably want to log this too
}
try {
    // Do the minimum acceptable
    return;
} catch (Exception e) {
    // if you don't have any more fallbacks, then throw an exception here
}
//More try catches?

Once you have it broken out like that, you could think about wrapping it up in a Strategy pattern.

interface DoSomethingStrategy {
    public void doSomething() throws Exception;
}

class NormalStrategy implements DoSomethingStrategy {
    public void doSomething() throws Exception {
        // do something
    }
}

class FirstFallbackStrategy implements DoSomethingStrategy {
    public void doSomething() throws Exception {
        // do something in the same line, but being less ambitious
    }
}

class TrySeveralThingsStrategy implements DoSomethingStrategy {
    private DoSomethingStrategy[] strategies = {new NormalStrategy(), new FirstFallbackStrategy()};
    public void doSomething() throws Exception {
        for (DoSomethingStrategy strategy: strategies) {
            try {
                strategy.doSomething();
                return;
            }
            catch (Exception e) {
                // log and continue
            }
        }
        throw new Exception("all strategies failed");
    }
}

Then just use the TrySeveralThingsStrategy, which is a kind of composite strategy (two patterns for the price of one!).

One huge caveat: don't do this unless your strategies are themselves sufficiently complex, or you want to be able to use them in flexible ways. Otherwise, you're larding a few line of simple code with a huge pile of unnecessary object-orientation.