问:
I need some help with defining a shell syntax
I'm trying to understand more about shells. I'm looking to implement one and want to look at what's been done in the past.

In a regular shell, you have features like aliases and relative paths, and strong syntactic conventions, like --flag and so on. The IPython community have added loads of nice features to their shells with only a tiny bit of new syntax.

Are there other projects that demonstrate innovative features, or novel use of syntax, that could be useful when designing a shell language?

As examples, the answers given below, on Boo and on Forth and Rebol, are perfect.

答:
Boo is a language that is used both as a scripting language, and as a platform for creating domain-specific languages.  Its manifesto describes why the author created it; Boo has:

A wrist-friendly, Python-like syntax

Syntactic sugar for common programming patterns

No variable declarations; assignments create locally-scoped variables automatically

Type inference

Type casting

Optional classes

First-class functions

Iterators (called Generators in Boo), with lazy execution

Duck typing

Access to the compiler pipeline

Boo is a .NET Framework language. It runs on Mono and so is cross-platform.

Boo is extensible, allowing you to create your own syntactical constructs.  There's even a book called DSLs in Boo: Domain-Specific Languages in .NET.

Boo can be used as a platform/engine for scripting.

There is also Lua, an embeddable, estensible, cross-platform scripting language with favorable performance characteristics. The Wikimedia Foundation has begun offering Lua as an alternative to their templating system.


问:
strategies for dealing with machine epsilon
Say you have a situation where you divide and then multiply a float, and you need to guarantee that it survives macheps (ie multiplication output equals division input). What are known strategies for guaranteeing this? Rounding would work, but anything else?</p>

答:
Traditionally, you multiply FIRST, and THEN you divide.

If your hardware and compiler are smart enough, the instructions emitted will preserve the full double-width result of the multiplication, for processing by the division.

Dividing first and then multiplying, you can't really do that.  (Your compiler MIGHT at that point be smart enough to reorder the operations, but you are usually safer doing it yourself.)

Read Hamming's Numerical Methods for Scientists and Engineers.  Early in the book, he goes into considerable detail on reorganizing your computations to reduce this kind of trouble.  It's available from Dover.  (If technical literature is your fetish, like it is mine, Dover is your FRIEND!)

ContentLicense: CC BY-SA 3.0


问:
In an interview, is it better to code a brute-force solution to a tough question, or to spend the interview examining the question carefully?
Sometimes interview questions are hard, whether the interviewer intends them to be, or not.  It can come down to a choice of whether to use the limited interview time to code up an ugly, inefficient, brute-force solution, or spend the time understanding every aspect of the problem with the interviewer.

For example, Problem 91 at Project Euler can be solved by a not-so difficult brute-force solution of calculating every possible triangle, writing an isRightTriangle() test, and popping all triangles that pass the test into a set.  But the two pair of X/Y coordinates make that an O(x^4) solution with a high constant value.  A friend and I just came up with a solution that is much more elegant and efficient, but the two of us spent 3 hours on it and drew dozens of diagrams, tested multiple formulae, examined multiple approaches, etc.

Not every interview question is fair.  Also what's easy for one person may be hard for another.  If someone struggles with a question, would you be more impressed by a brute force ugly solution that works?  Or excellent problem comprehension and in-roads toward an elegant solution, but no coded solution?  Is there a rule like after 20 minutes you should just start coding no matter what?

答:
Is there a rule like after 20 minutes you should just start coding no matter what?

No, but if you spend 20 minutes analyzing the problem before you get down to business, you're probably in trouble already. An employer who asks you a question like the one you cited is mostly interested in how you approach a problem, but if they ask it as a coding problem they'll want to see some code too. Talk them through your thought process...

Well, the obvious approach here is brute force. If I had a way to
  recognize a right triangle given the three vertices, I could run
  through all the combinations of two points and the origin looking for
  right triangles. That shouldn't be hard -- I can write a function that
  uses the Pythagorean Theorem to identify right triangles. To make that
  easier, I'll also write a function that determines the distance
  between two points using the distance formula...

Writing those functions should take about three minutes. Now, just a few minutes into the question, you've already shown that you remember basic geometry and that you really do know how to write code. It also gives you something to talk about:

So, we could obviously put the isRightTriangle(p1, p2, p3) function
  in the middle of four for loops and iterate over all the possible
  choices for each of the two variable points. Let's see... the problem
  asks for the number of right triangles including the origin on a 50x50
  grid, so using the brute force method makes us check 50 possibilities
  for each coordinate of each point. That's 50^4 checks... I'm sure we can
  do better, but the code is obvious, so let me write that down...

So now you write a function that uses nested for loops and the isRightTriangle() function that you just wrote. You've solved the problem, but you've also let the interviewer see where you're going. If their goal was just to see that you can write code, they might tell you to stop. More likely, they're happy to be talking to someone who knows what they're doing and they'll want to see how far you take this. So you go on...

It occurred to me while I was writing that that we can take advantage
  of symmetry. We can reflect any given right triangle around the 45°
  line, so if we choose to check one of the points only on one side of
  that line, we can just count any right triangles we find twice... once
  for the triangle and once for its reflection. That cuts the number of
  checks by half. Also, looking at it now, we're taking a square root to
  find the distance between two points, but then we just square that again
  in isRightTriangle()...

And so on. Again, they don't usually want to see a perfect solution, they want to see how you get to a solution. Your thought process doesn't have to be anything like the one above -- just having the confidence to think out loud will count for a lot. Don't sweat it if you make a mistake -- just say "hmmm, I think I've gone off the rails here -- let me go back a step..."


问:
How do you remember where in your code you want to continue next time?
When you interrupt the work on some code (be it because you have to work on something else or go on vacation or simply because it is the end of the day), once you close that Visual Studio project, what is your preferred way to remember what you want to do next when you start working on that code again.

Do you set a Visual Studio bookmark or do write down something like // TODO: continue here next time? Maybe you have a special tag like // NEXT:? Do you put a sticky note on your monitor? Do you use a cool tool or Visual Studio plugin I should know?

Do you have any personal trick that helps you find the place in your code where you left off the last time you worked on your code?

答:
Since you didn't say that you need to code to actually compile in both debug and release, one trick I often do is:

```<code>#if DEBUG
#error "YOU LEFT OFF HERE"
#endif
</code>```

Very tough to forget that. Otherwise, I would put a #pragma warning in the code so that it appears whenever you compile.

ContentLicense: CC BY-SA 2.5

Body:
Since you didn't say that you need to code to actually compile in both debug and release, one trick I often do is:

#if DEBUG
#error "YOU LEFT OFF HERE"
#endif

Very tough to forget that. Otherwise, I would put a #pragma warning in the code so that it appears whenever you compile.


问:
What's the practical difference between the styles of dependency injection?
I'm new to dependency injection and I have a few questions about which style I should use in my applications. I have just read Inversion of Control
Containers and the Dependency Injection pattern by Martin Fowler, but I
can't get the practical difference between constructor, setter and interface
injection.

It seems to me that the reasons for using one over the other are just a
matter of code cleaning and/or clarity. What is the difference? Are there any strong advantages or disadvantages to using one over the other, or is it just what I've stated before?

In my opinion, constructor injection is the most intuitive of all, as well as interface injection is the least. In the other hand, setter injection is a middle term, but, are you supposed to be able to change the instance of the dependency object you initially injected? Does this style of injection guarantees that the object which needs the dependency will always have it injected? I believe not, but please correct me if I'm wrong.

答:
Constructor Injection has the advantage that it makes the dependency explicit and forces the client to provide an instance. It can also guarantee that the client cannot change the instance later. One (possible) downside is that you have to add a parameter to your constructor.

Setter Injection has the advantage that it doesn't require adding a parameter to the constructor. It also doesn't require the client to set the instance. This is useful for optional dependencies. This may also be useful if you want the class to create, for example, a real data repository by default, and then in a test you can use the setter to replace it with a testing instance.

Interface Injection, as far as I can tell, is not much different than setter injection. In both cases you are (optionally) setting a dependency that can be changed later.

Ultimately it is a matter of preference and whether or not a dependency is required. Personally, I use constructor injection almost exclusively. I like that it makes the dependencies of a class explicit by forcing the client to provide an instance in the constructor. I also like that the client cannot change the instance after the fact.

Often times, my only reason for passing in two separate implementations is for testing. In production, I may pass in a DataRepository, but in testing, I would pass in a FakeDataRepository. In this case I'll usually provide two constructors: one with no parameters, and another that accepts a IDataRepository. Then, in the constructor with no parameters, I will chain a call to the second constructor and pass in a new DataRepository().

Here's an example in C#:

```<code>
public class Foo
{
  private readonly IDataRepository dataRepository;

  public Foo() : this(new DataRepository())
  {
  }

  public Foo(IDataRespository dataRepository)
  {
    this.dataRepository = dataRepository;
  }
}
</code>```

This is known as Poor Man's Dependency Injection. I like it because in production client code, I don't need to repeat myself by having several repeated statements that look like ```<code>var foo = new Foo(new DataRepository());</code>``` However, I can still pass in an alternate implementation for testing. I realize that with Poor Man's DI I'm hardcoding my dependency, but that's acceptable for me since I mostly use DI for testing.

ContentLicense: CC BY-SA 4.0

Body:
Constructor Injection has the advantage that it makes the dependency explicit and forces the client to provide an instance. It can also guarantee that the client cannot change the instance later. One (possible) downside is that you have to add a parameter to your constructor.

Setter Injection has the advantage that it doesn't require adding a parameter to the constructor. It also doesn't require the client to set the instance. This is useful for optional dependencies. This may also be useful if you want the class to create, for example, a real data repository by default, and then in a test you can use the setter to replace it with a testing instance.

Interface Injection, as far as I can tell, is not much different than setter injection. In both cases you are (optionally) setting a dependency that can be changed later.

Ultimately it is a matter of preference and whether or not a dependency is required. Personally, I use constructor injection almost exclusively. I like that it makes the dependencies of a class explicit by forcing the client to provide an instance in the constructor. I also like that the client cannot change the instance after the fact.

Often times, my only reason for passing in two separate implementations is for testing. In production, I may pass in a DataRepository, but in testing, I would pass in a FakeDataRepository. In this case I'll usually provide two constructors: one with no parameters, and another that accepts a IDataRepository. Then, in the constructor with no parameters, I will chain a call to the second constructor and pass in a new DataRepository().

Here's an example in C#:

public class Foo
{
  private readonly IDataRepository dataRepository;

  public Foo() : this(new DataRepository())
  {
  }

  public Foo(IDataRespository dataRepository)
  {
    this.dataRepository = dataRepository;
  }
}

This is known as Poor Man's Dependency Injection. I like it because in production client code, I don't need to repeat myself by having several repeated statements that look like
var foo = new Foo(new DataRepository());
 However, I can still pass in an alternate implementation for testing. I realize that with Poor Man's DI I'm hardcoding my dependency, but that's acceptable for me since I mostly use DI for testing.


答:
Have you considered an extremely simple language syntax, like FORTH or REBOL? These are extremely easy languages to understand, and the grammars are very simple to implement.

In these languages, functionality is described in terms of words, which are themselves defined in terms of simpler words, making it incredibly simple to construct powerful abstractions, without the complexity of understanding classes, types, or even functions.

FORTH is so simple, that a full compiler can be written in a few hundred lines of code. A revision of Crenshaw's book demonstrates this. (Sample implementations are commonplace.) REBOL is similarly simple, and while it has only recently been open-sourced, and hasn't yet been retooled for embedding, the core language parser weighs in at about 1,000 lines of code. From the other side, both are easy to learn and grasp, since there are only a few concepts to understand.

Both languages are suitable for implementation as a shell language, as the host environment can define whatever words are needed for common operations. From there, users can do literally anything they can imagine.

Title: I need some help with defining a shell syntax

Body:
I'm trying to understand more about shells. I'm looking to implement one and want to look at what's been done in the past.

In a regular shell, you have features like aliases and relative paths, and strong syntactic conventions, like --flag and so on. The IPython community have added loads of nice features to their shells with only a tiny bit of new syntax.

Are there other projects that demonstrate innovative features, or novel use of syntax, that could be useful when designing a shell language?

As examples, the answers given below, on Boo and on Forth and Rebol, are perfect.


答:
This is now an integrated feature in Visual Studio 2012 where you can suspend and resume your workspace. Suspend will take a snapshot of your open files, breakpoints, watch list, work items etc. and resume will bring it back. Basically your entire work context is saved and will resume exactly as you left.

http://msdn.microsoft.com/en-us/library/ms181403.aspx

A short video showing the feature is here

http://channel9.msdn.com/Series/Visual-Studio-2012-Premium-and-Ultimate-Overview/Visual-Studio-Ultimate-2012-How-to-multi-task-with-My-Work

Title: How do you remember where in your code you want to continue next time?

Body:
When you interrupt the work on some code (be it because you have to work on something else or go on vacation or simply because it is the end of the day), once you close that Visual Studio project, what is your preferred way to remember what you want to do next when you start working on that code again.

Do you set a Visual Studio bookmark or do write down something like // TODO: continue here next time? Maybe you have a special tag like // NEXT:? Do you put a sticky note on your monitor? Do you use a cool tool or Visual Studio plugin I should know?

Do you have any personal trick that helps you find the place in your code where you left off the last time you worked on your code?


答:
I use several tricks:

Place @@ in code comments or in a document for things that need to be done in the current iteration but not immediately. No code or document leaves my machine if it contains @@.

That one specific place that I need to contine on working tomorrow morning I mark with @@HERE. This is seldom necessarry because my IDE will open where I close earlier, and you can even tell Word to do so.

All things that should be fixed/added later go into a proper bug tracking system or are in design documents.

And are you sure your Visual Studio cannot remember the last location your were working on? "Suspending Work with Visual Studio 2012" says it can be done in 2012 (Google for Visual Studio start "left off")


问:
Joda Time vs Java Time
Although Joda is feature rich and more sophisticated than standard Java time, it may not always be the best thing to use. How do I decide if I should use Joda Time or Java Time in any Java code?

Is there some kind of guideline which tells us how to pick the right one depending on our requirements?

答:
Java 8 and Later

Use the Date & Time API included in java.time.*. It's heavily influenced by Joda Time. In fact the main author is Stephen Colebourne, the author of Joda Time.

Prior to Java 8

Joda Time is such an improvement over the Java legacy time library (java.util.Date and java.util.Calendar) that it is almost always the right choice, apart from the following exceptions:

When it is difficult or undesirable to add third party dependencies to your project

When its use in a public interface would cause issues, e.g. getting an ORM to handle both java and Joda time fields

However, in the case of 2) it would still be better to use Joda internally if possible.

Title: Joda Time vs Java Time


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
Any teenage kid who hacks with computers is equivalent (or superior) in skill to a veteran working programmer.

My 14 year old nephew is good with
  computers and I'm paying him $10/hr to
  mow my lawn. Why should I pay you six
  figures to write the next FaceBook?


答:
Actually this error happens not only because of multiplication, it can be reproduced by a simplier way: 0.1 + 0.2

There is a special website for this issue: http://floating-point-gui.de/

What can I do to avoid this problem?

That depends on what kind of calculations you’re doing.

If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype.

If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places
  when displaying it.

If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But
  this is more work and has some drawbacks.

Title: strategies for dealing with machine epsilon

Body: Say you have a situation where you divide and then multiply a float, and you need to guarantee that it survives macheps (ie multiplication output equals division input). What are known strategies for guaranteeing this? Rounding would work, but anything else?</p>


问:
Class of problems solvable by sed or stream editors
I've came across a question transform this text with sed [sed only]
and it got me wondering what class of problems is solvable by stream editors or programs/computational models with similar constraints.

For E.g Regular expressions can solve problems that require fixed/const amount of memory (Can solve all problems that have a Deterministic Finite state automa)

My question is what are the computational limits/constraints of sed in particular and any stream editor in general and what class/classes of problems can be solved by it?
(after mapping it some text alphabet set if need be)

答:
First of all, I would say that "can be done (or solvable)" != "best choice"

Let's see some examples:

You mentioned regex. Regex can detect prime numbers. Would you use regex for it?

text processing with some math calculation, can be done by sed too. however, if awk is available, would you go with sed?

also something like, parsing a text with a certain pattern, when 3rd match, do A, 6th match, do B, xth match do Y. this can be done by sed as well by playing with hold space. but think about it how straightforward if you use awk to solve it.

think about writing a normal for(i=1;i<100;i++)  loop with sed

gnu sed supports passing matched part to external programs to do further processing then get result back. (like system() or getline in awk) So you could imagine what kind of problems sed can do if your sed is backup-ed with bc, sed, nl, seq, join, cut, sort, paste, grep even cp, mv, rm, find... and awk

The best choice for same problem could be different to different people. say a problem, sed is the best choice from your point of view. However he is not good at sed, but knows awk well, he thought awk is best choice. She knows python well.. and I am an expert of MS-Excel....

my 2cents.

OwnerDisplayName: Ayos

OwnerDisplayName: Kent


问:
How often is Inheritance used?
I admit that I am a junior developer, and so far I've only built simple web applications in ASP.NET MVC. But I've never had to use the inheritance aspect of Object Oriented Programming in my own classes! It is true that in using ASP.NET MVC I inadvertently use inheritance (any controller I create will inherit from the base controller class), but I am referring here to the conscious use of inheritance in my design of a particular web system.

Is it because I am a bad programmer? Or could it be that inheritance only comes into play in certain scenarios? Don't get me wrong, I understand what inheritance is and how to code using inheritance if I had to.

I just can't seem to find a scenario to use it at. Basically, I am wondering how often it is used in OO programming in general.

答:
Inheritance is mostly used in framework-based development, where you most often don't define your own classes, but extend existing ones:

Asp.Net MVC - Controllers

Ruby on Rails - Controllers and ActiveRecords

Android - Activities, AsyncTasks, Adapters

WPF and Windows Phone - Windows, UserControls, Controls, Pages

If you write a code which isn't related with frameworks, you can do it without inheritance by using the composition pattern.

Title: How often is Inheritance used?


答:
The differences between constructor and setter injection are already adequately described above, so I won't elaborate further on them.

Interface injection is a more advanced form of injection that is useful because it allows the dependency to be decided at the moment it is used rather than during initialisation of the object that will use it.  This allows a number of useful options:

The dependency could be scoped differently to the object it is injected in; for instance you can use interface injection to provide an object for which one exists per user session or per thread to a global singleton.  Each time the object needs the dependency, it will call the getter method provided by the framework, and this can return different results depending on the situation in which it is called.

It allows for lazy initialization -- there is no need for the dependency to be initialized until it is about to be used

It allows dependencies to be loaded from a cached copy when they exist or reinitialised when they don't (e.g. using a SoftReference in Java).

Obviously advanced techniques like this have downsides; in this case, the main problem is that code becomes less clear (classes used in your code become abstract, and there is no obvious concrete implementation of them, which can be confusing if you aren't used to it) and you become more dependent on your dependency injection framework (it's still possible to instantiate your objects manually, of course, but it is harder than with other injection styles).

Title: What's the practical difference between the styles of dependency injection?

Body:
I'm new to dependency injection and I have a few questions about which style I should use in my applications. I have just read Inversion of Control
Containers and the Dependency Injection pattern by Martin Fowler, but I
can't get the practical difference between constructor, setter and interface
injection.

It seems to me that the reasons for using one over the other are just a
matter of code cleaning and/or clarity. What is the difference? Are there any strong advantages or disadvantages to using one over the other, or is it just what I've stated before?

In my opinion, constructor injection is the most intuitive of all, as well as interface injection is the least. In the other hand, setter injection is a middle term, but, are you supposed to be able to change the instance of the dependency object you initially injected? Does this style of injection guarantees that the object which needs the dependency will always have it injected? I believe not, but please correct me if I'm wrong.


答:
The Java standard date API is so fundamentally broken that I have often considered simply adding Joda Time to the library extensions of the JVM so that it loaded on the classpath by default with the rest of the Java API.

If you have ever been tasked with retrofitting internationalization and time zones into a legacy Java application and have attempted to use the standard Java API alone, you will understand what I mean.  I was able to turn thousands of asinine lines of code into less than a hundred.  The productivity boost is inconceivable.

Further the standard Date API is not intuitive, where the fluid Joda API can be picked up in hours not weeks.  Your analogy of trying to get to the island that is two miles away, is more akin to the following.

1) A motorboat that will get you to the island in only 6 minutes.

Or...

2) A makeshift bamboo raft tied together with vines during a hurricane steered by a crazy guy whose best friend is a volleyball.

As other answers have stated, the few drawbacks such as the ORM are even becoming non-existent as Hibernate now has plugins that allow for Joda type bean properties to be mapped to database date/time fields.  JPA might also have an answer for this as well.

If your desire is for your application to have a minimalist footprint as a desktop application as it pertains to disk space then perhaps Java is not even the right language choice.

Title: Joda Time vs Java Time

Body:
Although Joda is feature rich and more sophisticated than standard Java time, it may not always be the best thing to use. How do I decide if I should use Joda Time or Java Time in any Java code?

Is there some kind of guideline which tells us how to pick the right one depending on our requirements?


问:
Kiln - Mercurial and Git limitation
According to this blog post: Kiln now supports repositories accessible from both Git and Mercurial

We decided that the awesome way would be to make Kiln fully bilingual.
  It stores every repo in both formats. It automatically converts
  everything back and forth, always. The translation is 1:1, reversible,
  and round-trippable. Whatever you do to a Kiln repository using Git
  will be immediately visible to Mercurial users and vice versa.

I can't imagine that everything runs smoothly. What limitations does this have?

答:
The limitation is if you need to convert between the two, you have to go through the central server that knows the mapping.  You can't just push directly from your local git repo to your colleague's hg repo, like you can with pure git or pure hg.

Other than that, there aren't too many technical issues to overcome.  Git and mercurial both have a commit as a fundamental unit and create a directed acyclic graph between the commits to represent branches.  They both have universally unique identifiers for commits that include all the history leading up to them.

Now, two version control systems that aren't as similar would create more problems.  The next level of difficulty would be a VCS like perforce, which has commits as a fundamental unit, but treats branches somewhat differently.  A VCS like subversion, which has file revisions as a fundamental unit, would be very difficult indeed to keep a reversible mapping with.

Title: Kiln - Mercurial and Git limitation


问:
How to deal with complex codes in (huge) projects
I am preparing a memoir about "Why do (some) IT projects become too complex and how to avoid it ?".

If you have ever encountered projects having complex codes or were hard to maintain, how did you manage to go through it?

If you have to choose between several applications to use in your project, what would be your top priority in their functionality and why?

答:
technical debt

refactor to eliminate

business changes

adapt and expunge

tool changes

new tools, same old architecture = impedence mismatch


问:
Java Xml intraction in Android
I'm working on Android application development. There is a question that always comes to my mind that: How XML interacts with Java code?. I mean Button inside XML is a view, but Button inside Java is a class.

For populating and XML layout we use setContentView(R.layout.name). What I want to know is how this XML code interacts with Java, what technique is used and what code is behind this. If any know please tell me in brief.

答:
To summarize in short, an XML layout is a way of separating the construction of View hierarchy from Android/Java code. This helps you in modifying and editing the UI layout easily.

When you set an XML layout using setContentView(R.layout.mylayout) the Android will internally inflate the mylayout.xml and build a LinearLayout class and adds it to the View Root.

Title: Java Xml intraction in Android


问:
When and why would we use immutable pointees?
In Java, the String object is both immutable and also a pointee (aka reference type). I'm sure there are other types/objects which are both immutable and a pointee as well and that this extends further than just Java.

I can not think where this would be desirable possibly due to my own experience I've only  used either reference types OR immutable primitive types.

Can some one please give me a situation where it would be useful so I can get an appreciation for their meaning/value/concept.

答:
First let's consider why it is useful to have strings that are immutable.  Consider the following sketch:

```<code>void Safe(string s)
{
    if (!SecurityCheck(s)) { throw new SecurityException(); }
    Dangerous(s);
}
</code>```

Method Safe checks to see whether string s is "safe". Perhaps by "safe" we mean "the user is permitted to access this database table", or "the string contains no HTML that could be used in a cross-site scripting attack", or whatever. Only if the string is safe is it passed to a method that does something dangerous with it.

If strings were mutable then a clever attacker could pass a "safe" string and then after the security check, mutate the string to a "dangerous" string. Getting the timing right might be tricky, but of course attackers get to try multiple times, and they only have to succeed once.

This illustrates the first value of immutable data: facts deduced in the past about the data remain true in the future. If you have an immutable queue and you ask how many elements are in it, the answer you got five thousand nanoseconds ago is still correct. This enables you to make computations with confidence.

The second great value of immutable data is that it enables persistence. By persistence I don't mean ability to serialize to disk (though that is handy) but rather ability to re-use a portion of a data structure when building a larger data structure. If you have a large immutable tree and you would like it to be a sub-tree of a larger tree, no problem. You know that it's not going to change, so you can safely share the data. But if you have, say, a mutable queue and you'd like to use its contents in another data structure, you're going to have to make a copy.

That's just a brief sketch; see my series of articles on immutable data structures for more details:

Link

Body:
First let's consider why it is useful to have strings that are immutable.  Consider the following sketch:

void Safe(string s)
{
    if (!SecurityCheck(s)) { throw new SecurityException(); }
    Dangerous(s);
}

Method Safe checks to see whether string s is "safe". Perhaps by "safe" we mean "the user is permitted to access this database table", or "the string contains no HTML that could be used in a cross-site scripting attack", or whatever. Only if the string is safe is it passed to a method that does something dangerous with it.

If strings were mutable then a clever attacker could pass a "safe" string and then after the security check, mutate the string to a "dangerous" string. Getting the timing right might be tricky, but of course attackers get to try multiple times, and they only have to succeed once.

This illustrates the first value of immutable data: facts deduced in the past about the data remain true in the future. If you have an immutable queue and you ask how many elements are in it, the answer you got five thousand nanoseconds ago is still correct. This enables you to make computations with confidence.

The second great value of immutable data is that it enables persistence. By persistence I don't mean ability to serialize to disk (though that is handy) but rather ability to re-use a portion of a data structure when building a larger data structure. If you have a large immutable tree and you would like it to be a sub-tree of a larger tree, no problem. You know that it's not going to change, so you can safely share the data. But if you have, say, a mutable queue and you'd like to use its contents in another data structure, you're going to have to make a copy.

That's just a brief sketch; see my series of articles on immutable data structures for more details:

Link


问:
Limit number of users in a web app?
I've been asked to look at converting our traditional client-server software into a web-based version (using PHP).

One of the first questions from management was how we'd limit the number of concurrent users, currently handled by our licence manager that every client connects to when running our apps.

My initials thoughts:

Check the number of open sessions on the server (only with valid users that have logged in).

Logging each login/logout to a DB table and counting them.

Is there a standard/best practice way of limiting the number of concurrent users who can log into a web app?

答:
Be very very very careful with this.  Make sure you have an idle session timeout and that you know what it is.  Document it.  Configurable would be great too.

The reason why this is dangerous on the web is that the lifecycle of a session is not as simple as it appears.  People tend to evaluate sessions based on the happy path.  User logs in, then logs out.

But some things to consider:

When does a session begin?  Sessions do not begin at login.  They begin at first HTTP request.  Even if login is the first page visited, what if 100 users visit the site but then instead of logging in, leave?  You have 100 sessions that are essentially "lost".

What if users never log out, but simply close their browser?

Can a user login to the same user account from two different HTTP sessions?  If not, what if the existing session isn't active any more.  If a user logged in, closed their browser, started up the browser again, they would be unable to login until their previous session "times out" on the web server.

I have seen some of these concerns handled.  It can be done.  But it's complicated, so be warned.

If you choose the counting logins and logouts in the database approach, you still have some of the same problems.  What if a user never logs out, but the session times out?  I have seen this solved in Java EE by defining a SessionBindingListener, so that when a session times out, we can go to the database and invalidate their login.  I'm not sure if PHP can do the same thing.  As PHP code is only invoked when an HTTP request comes in, I doubt it can be done.  But I am not a PHP expert.

Title: Limit number of users in a web app?


答:
Well, I know at least one limitation of Git-HG conversion: Git stores less metadata in changeset for the same data, than Mercurial. And it can be easy detectable in handling of named branches (in Mercurial) and "just branches" of Git.

Conversion Git -> Mercurial -> Git lost nothing, repository before and after will be identical and equal

Conversion Mercurial -> Git -> Mercurial will have less data in final repository (branch-name is permanent attribute of any Mercurial changeset, Git branches are more Mercurial's "bookmark" - non-master changeset lost information about branch)

Longer text (with lost pictures, sadly)

Title: Kiln - Mercurial and Git limitation

Body:
According to this blog post: Kiln now supports repositories accessible from both Git and Mercurial

We decided that the awesome way would be to make Kiln fully bilingual.
  It stores every repo in both formats. It automatically converts
  everything back and forth, always. The translation is 1:1, reversible,
  and round-trippable. Whatever you do to a Kiln repository using Git
  will be immediately visible to Mercurial users and vice versa.

I can't imagine that everything runs smoothly. What limitations does this have?


问:
The way to describe the scale of software in the CV
I'm writing my CV, and having trouble explaining about the software for enterprise I developed in my previous job. Now I'm thinking of writing following 4 things for each software.

Abstract explanation about what the software is used for

How much was the software sold

About how many data does the software usually handle

About how many DB tables does the software have

Are there any inappropriate ones in these?
Or, anything I should add?

答:
If you simply label the software you've developed/been on teams that developed as "enterprise", the person reviewing your CV either knows what that means or doesn't, and neither situation requires you to spend any time (or space) going into detail on longer than a single bullet point.

If the person reviewing your CV doesn't know what it means, they're probably doing the basic screening and are simply looking for the keyword "enterprise" (if even that) and the specifics of the development don't matter one bit to them and wouldn't make a difference in you advancing or not.

If the person reviewing your CV does know what it means (for instance, if I'm reviewing your resume), I'm fine just seeing "enterprise" on there and if you get to the next stage of the interview process because of all of the other good stuff on your resume, then I'll ask you about it if I need to.  When I do ask, I would probably want to know about the number of concurrent users and data storage and transfer mechanisms -- things that are directly applicable to software you'd be building for me.

So, if you were to go into any greater detail than "developed enterprise applications", a single bullet point that said something like "Led a team that developed an enterprise application that handled n concurrent users and handled xGB of data daily" would be helpful yet concise, and anything beyond that I'd wonder if you'd freely discuss the intricacies of all applications you've developed out there on your CV (there are often NDAs about such things, after all).


问:
Why Java does not support private/protected inheritance like C++?
While inheriting a class in C++, user can specify the access specifier like,

```<code>class Base
{
    public int mem1;
    protected in mem2;
};

class Derived1 : **private** Base
{
    // mem1 will be private here.
    // mem2 will be private here.
};

class Derived2 : **protected** Base
{
    // mem1 will be protected here.
    // mem2 will be protected here.
};

class Derived2 : **public** Base
{
    // mem1 will be public here.
    // mem2 will be protected here.
};
</code>```

But the same is not possible in Java, i.e. extends in java is always like "public" inheritance in C++.

Could someone explain the reason for this?

答:
Most of the benefits that private / protected inheritance give you can be easily achieved through encapsulation. Thomas Eding has provided some good examples of cases that could be made easier with the addition of private / protected inheritance, and while these are valid cases, workarounds exist that do not require private / protected inheritance and are more 'idiomatic' (in Java at least).

The developers of the Java language evidently felt that the cost in complexity needed to support  private / protected inheritance (including multiple inheritance) outweighed the benefit that it would provide.


答:
When I'm screening resumes (note resumes not CVs, and yes they are different), I don't necessarily care to read a dissertation on the overall product you wrote for.  I care a lot more about what you actually did while you were on the project.  I have seen too many candidates relying upon presumed transference to add a degree of undeserved credibility.  Just because you worked on a large project doesn't mean you had the skills to create that large project.

For example: "So it's nice that you worked on a project with 10M+ loc, but you were only there for 6 months. Tell me what you did because I know you didn't write all 10M+ lines."

That having been said, having a rough sense of scale about the project provides a degree of perspective about the challenges you faced.  Large teams have different development patterns than smaller teams do.  Do try to use specifics but don't get overly specific.

This is bad:  "Product XYZ had $420M in annual revenues with 250 developers and 18.2M loc along with 86 independent DB tables and 79 subordinate tables and is capable of processing up to 1.48 tera-transactions per second."

This is better: "Product XYZ provides __ services and had approximately 18.2M loc."  Or tables instead of code if it's a SQL / DB heavy job you're applying to.  Or number of devs if the focus is on teamwork.  Or ... based upon the job req.  Note the "or" in each of those cases.

The guiding principle is to be mindful of the reviewer's time.  Make it easy for them to figure out what you contributed.  Your CV is about you not the product you were on.

As an aside, bigger software products need less description.  If the interviewer wants to know, they'll google it.  And that's a good thing because it meant the rest of your resume got them interested in talking to you and now they're doing background work on you.  And yes, the good companies will try to dig up additional information.

To answer your question directly:

From one point of view, you're going about it wrong and focusing on the wrong thing.  You're focusing on the product instead of yourself.

However, smaller, more obscure product need a little bit of description.  The items you suggested are sufficient.  Just remember to keep the description concise.

A resume is a one or two page document that gives highlights about what you've done, with a focus on the last 10 years or so.  Judicious use of page real-estate is critical in crafting a proper resume.

A C.V. is a much longer document that reflects a lot more about you than a resume ever could.  Page real-estate is still important, but the criticality is not as great.  If you bump into an extra page on a C.V. then it's not as big of a deal.

Use between the two is highly culture specific.  In the US, resumes are the norm and a proper CV would likely get tossed without review.

Title: The way to describe the scale of software in the CV

Body:
I'm writing my CV, and having trouble explaining about the software for enterprise I developed in my previous job. Now I'm thinking of writing following 4 things for each software.

Abstract explanation about what the software is used for

How much was the software sold

About how many data does the software usually handle

About how many DB tables does the software have

Are there any inappropriate ones in these?
Or, anything I should add?


答:
Your question tells me, you should really read Effective Java by Joshua Bloch. First edition is available online as PDF for free for example here as PDF (note: especially the singleton chapter is outdated, and other newer stuff is missing, so consider getting 2nd edition if you like the book). Every Java programmer, even experienced ones, who has not done so yet should go through the items of the book at least at a glance, and study carefully everything they don't already know.

In 1st ed. Item 13 in Chapter 4 is title "Favor Immutability" and goes over the subject at more length than is sensible in an answer here. But in short, you should rather be asking, why are there reference types which are not immutable. Short list of benefits of immutability: simple in multiple ways, inherently thread-safe.

Only drawback of immutable objects is: if you want to change some property of immutable object, you must create a new object, like snippet String s=""; s=s+5; does: It first has empty string instance, then it creates new string instance with value "5"). Also, singletons which have changing state can't be immutable, for obvious reason.

Title: When and why would we use immutable pointees?

Body:
In Java, the String object is both immutable and also a pointee (aka reference type). I'm sure there are other types/objects which are both immutable and a pointee as well and that this extends further than just Java.

I can not think where this would be desirable possibly due to my own experience I've only  used either reference types OR immutable primitive types.

Can some one please give me a situation where it would be useful so I can get an appreciation for their meaning/value/concept.


问:
A* Algorithm Completeness Proof
The A* Algorithm is the optimal (provided the heuristic function is underestimated), complete & admissible (provided some conditions). I know the proofs of admissibility & optimality.

But how do you prove that the A* Algorithm is complete?

答:
For a proof of completeness, it is not necessary to look specificially at A*. Any finite graph search algorithm using a node queue where you take one element from, generate all children of that graph node and put them back into the queue is complete, "A*" is just a special case of that kind of algorithms.

Once you got this, it is easy to find a proof of completeness for arbitary graph search by Google, for example, this one:

http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-410-principles-of-autonomy-and-decision-making-fall-2010/lecture-notes/MIT16_410F10_lec04.pdf

The proof itself is not very complex, but IMHO still too long for summarizing it here.

Title: A* Algorithm Completeness Proof


答:
I use sed primarily in a *nix environment where the problem to be solved is a straightforward data transformation problem. For example, adding or removing columns from .csv data or modifying an existing date in a field. Also, sed is warranted where writing another piece of software written in Python, Perl, Clojure, awk, or your favorite language does not support the overhead of another module's maintenance.

I have not used sed's advanced features, like swapping registers, and probably will not, because going beyond a simple data transformation would warrant the overhead of a more fully fledged program.

Title: Class of problems solvable by sed or stream editors

Body:
I've came across a question transform this text with sed [sed only]
and it got me wondering what class of problems is solvable by stream editors or programs/computational models with similar constraints.

For E.g Regular expressions can solve problems that require fixed/const amount of memory (Can solve all problems that have a Deterministic Finite state automa)

My question is what are the computational limits/constraints of sed in particular and any stream editor in general and what class/classes of problems can be solved by it?
(after mapping it some text alphabet set if need be)


答:
One more point:
Java-Time (i.e. Date) is not ThreadSafe but JodaTime is.
So JodaTime is preferred when requirements like

MultiThreaded Environment accessing the common resources

Centralized Time Synchronization like situations

Or else for simple applications Java-Time is okay.

Title: Joda Time vs Java Time


答: As Java does not have multiple inheritance and everything has to be (publicly) inherited from Object, there are no places in Java where private or protected inheritance would yield a valid program.

Title: Why Java does not support private/protected inheritance like C++?

Body:
While inheriting a class in C++, user can specify the access specifier like,

```<code>class Base
{
    public int mem1;
    protected in mem2;
};

class Derived1 : **private** Base
{
    // mem1 will be private here.
    // mem2 will be private here.
};

class Derived2 : **protected** Base
{
    // mem1 will be protected here.
    // mem2 will be protected here.
};

class Derived2 : **public** Base
{
    // mem1 will be public here.
    // mem2 will be protected here.
};
</code>```

But the same is not possible in Java, i.e. extends in java is always like "public" inheritance in C++.

Could someone explain the reason for this?


答:
I think that you're asking a question for which there is actually no answer, much less a 'right' answer.  The reason I say this is that it depends entirely on what the person asking the question values.

It's possible the interviewer is a hardcore pragmatist really looking to see that you'll get something working quickly and then optimize as a lower priority activity if you have remaining time.  It's equally possible that the interviewer is doing his best impression of google's hiring practices and isn't interested in anything but the sexiest, most elegant algorithm and takes it as a sign of weakness that you'd ever put the words "brute" and "force" within 5 words of one another.  It's also just as possible that the interviewer googled "interview questions" and found this problem on the internet 5 minutes before you came in and has no idea what he wants.

In all cases, your best bet is probably to ask for clarification, if you can't infer based on context information what the interviewer wants.  You're right that not all interview questions are fair, and, in fact, not all of them are good questions or even questions that make sense.  An interview is an inherently reductionist activity, much like "speed dating" where you're spending an hour or two with someone and the two of you are trying to guess, based on that hour, whether you'll work well together for the next 5 years or not.  Examined from that perspective, I hope it's clearer why I say there's really no answer to your question about a 'rule'.

Someone is asking you a question they think will give you insight into your competence and fit with their team.  You have to look at their team, what you know about them, the interviewer's personality, and dozens of other factors, and make a best guess as to what answers, approach, and process they would be likely to value.  Personally, I'd say that you should approach it in the way that you think is the best idea.  If they don't agree with you, it might not have wound up being a good fit anyway -- easier to figure that out earlier than later.

Title: In an interview, is it better to code a brute-force solution to a tough question, or to spend the interview examining the question carefully?

Body:
Sometimes interview questions are hard, whether the interviewer intends them to be, or not.  It can come down to a choice of whether to use the limited interview time to code up an ugly, inefficient, brute-force solution, or spend the time understanding every aspect of the problem with the interviewer.

For example, Problem 91 at Project Euler can be solved by a not-so difficult brute-force solution of calculating every possible triangle, writing an isRightTriangle() test, and popping all triangles that pass the test into a set.  But the two pair of X/Y coordinates make that an O(x^4) solution with a high constant value.  A friend and I just came up with a solution that is much more elegant and efficient, but the two of us spent 3 hours on it and drew dozens of diagrams, tested multiple formulae, examined multiple approaches, etc.

Not every interview question is fair.  Also what's easy for one person may be hard for another.  If someone struggles with a question, would you be more impressed by a brute force ugly solution that works?  Or excellent problem comprehension and in-roads toward an elegant solution, but no coded solution?  Is there a rule like after 20 minutes you should just start coding no matter what?


问:
Have they missunderstood currying or have I?
This question is similar to the question posted on Does groovy call partial application 'currying'?, but not completely the same, and the answers given there do not really satisfy me.

I would like to state right at this point, before I go any further, that currying is one of the concepts that have been hard to fully understand. I think the reason for that is the fact that there seem to be two general definitions of currying, and they don't really mean the same thing both in theory and in application.

That being said, I think currying is a very simple concept once you decide to take only one of the two definitions and stick to it. In fact, currying should not be difficult to understand at all, but in my experience, understanding currying has been the equivalent of showing a little boy an apple and telling him that fruit is called apple, and then you go on calling that fruit an orange. The boy will never understand the simple concept of an apple because you have caused an enormous amount of confusion by calling the apple an orange.

The definition of currying that I've accepted as the right one is that currying is taking a function of an arbitrary arity and turning it into multiple chainable functions each of which accepts only one parameter (unary functions). In code, it would look like this:

```<code>f(1,2,3);
//becomes
f(1)(2)(3);
</code>```

However, some people, including well known programmers like John Resig, explain currying as something completely different. For them, currying is no more than simple partial application. There is even a generally accepted javascript function for currying:

```<code>Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };
</code>```

This functions does not really curry anything, but rather partially applies the supplied arguments. The reason why I don't think this function curries anything is because you can end up with a function that accepts more than one argument:

```<code>var f2 = f.curry(1); //f accepts 3 arguments f(1,2,3);
f2(2,3); // calling the resulting "curried" function.
</code>```

So, my question is, have I misunderstood currying or have they?

I will leave you with this post that explains currying in javascript, but in a way in which I don't really see any currying: https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/

答:
I think both things are very closely related, and in the case of a two-argument function fundamentally the same really, although you could call the first thing you wrote as “complete” and the second one as “partial” currying, which would more precisely be called a special form of partial application or binding, always considering the first parameter.

In your example, f2 is f(1) in the syntax you used above, and f2(2,3) can be read simply as syntactic sugar(!) for f2(2)(3). To me, currying is not so much about the mechanics of telling your language that you want to give the arguments one after the other – that is absolutely useful, no doubt, but just a special case of binding any one argument. The importance of currying, in my eyes, is as a theoretical construct that allows you to just consider one-argument functions, because everything else can be reduced to that anyway.


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
My CV has a "Languages and Frameworks" section that looks something like this:

ECMAScript/Javascript (JQuery, Qooxdoo, YUI)

C++ (Qt, STL, ATL, MFC)

Python (Wx)

XML, XSLT, XSD

This is for three reasons:

Although no one would expect you to have experience using JQuery or YUI in C++, this does help disambiguate your hypothetical experience of Qt in C++ from your lack of experience in Wx in C++.  Simply placing Wx or Qt in a later bundle of frameworks doesn't do this.

It gives a concise headline for each category, so that a knowledgeable recruiter can scan it to find what they want, whilst still filling it with enough buzzword to get your CV to get past recruitment bots.

By not calling this section "programming languages", I also get to avoid being roundfiled by someone who disagrees with my assertion about whether or not XSLT is a programming language.  Not to mention those who maintain an arbitrary distinction between Programming and Scripting languages.


答:
You are right in saying that what many (if not most) people in the JavaScript community refer to as currying does not really correspond to the term as defined in Haskell.

Then again, neither does partial application. A partial application of all arguments is a full application, but this in not happening here, because if you do this for all arguments, you will still not have applied the function, but rather created a niladic function from it (a distinction that makes no sense in Haskell).

At the bottom line, for a JavaScript programmer it's more important to understand what other JavaScript programmers mean by "currying" or "partial application", than what a non-JavaScript programmer use the term for.

FIY, I think the correct (and not unheard of) term here is binding. You bind the arguments of a function. In particular, you can also bind the implicit this argument of a function.

Title: Have they missunderstood currying or have I?

Body:
This question is similar to the question posted on Does groovy call partial application 'currying'?, but not completely the same, and the answers given there do not really satisfy me.

I would like to state right at this point, before I go any further, that currying is one of the concepts that have been hard to fully understand. I think the reason for that is the fact that there seem to be two general definitions of currying, and they don't really mean the same thing both in theory and in application.

That being said, I think currying is a very simple concept once you decide to take only one of the two definitions and stick to it. In fact, currying should not be difficult to understand at all, but in my experience, understanding currying has been the equivalent of showing a little boy an apple and telling him that fruit is called apple, and then you go on calling that fruit an orange. The boy will never understand the simple concept of an apple because you have caused an enormous amount of confusion by calling the apple an orange.

The definition of currying that I've accepted as the right one is that currying is taking a function of an arbitrary arity and turning it into multiple chainable functions each of which accepts only one parameter (unary functions). In code, it would look like this:

```<code>f(1,2,3);
//becomes
f(1)(2)(3);
</code>```

However, some people, including well known programmers like John Resig, explain currying as something completely different. For them, currying is no more than simple partial application. There is even a generally accepted javascript function for currying:

```<code>Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };
</code>```

This functions does not really curry anything, but rather partially applies the supplied arguments. The reason why I don't think this function curries anything is because you can end up with a function that accepts more than one argument:

```<code>var f2 = f.curry(1); //f accepts 3 arguments f(1,2,3);
f2(2,3); // calling the resulting "curried" function.
</code>```

So, my question is, have I misunderstood currying or have they?

I will leave you with this post that explains currying in javascript, but in a way in which I don't really see any currying: https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/


答:
The way that I would implement this is not at session start, but when a user first logs in to the application.

The approach that I would take would be a sliding token that gets updated with each authenticated users HTTP request.

You could either write a CRON job or invoke a script at each request to quickly delete expired tokens from the database.

This would allow you to operate logins separately from sessions, as a session starts for each unique user who connects. It would also allow you to operate a token based on a user and allow each user multiple logins. Of course, this may not be a requirement, but at least the same user logging in on the one machine in two web browsers could count for one license.

Bare in mind too that if you are going to be deploying this within enterprises you may want to look at obfuscation of your code to prevent tampering / viewing.

Title: Limit number of users in a web app?

Body:
I've been asked to look at converting our traditional client-server software into a web-based version (using PHP).

One of the first questions from management was how we'd limit the number of concurrent users, currently handled by our licence manager that every client connects to when running our apps.

My initials thoughts:

Check the number of open sessions on the server (only with valid users that have logged in).

Logging each login/logout to a DB table and counting them.

Is there a standard/best practice way of limiting the number of concurrent users who can log into a web app?


问:
Solutions for "Maintenance Mode"
Given a web application running across 10+ servers, what techniques have you put in place for doing things like altering the state of your website so that you can implement certain features.

For instance, you might want to:

Restrict Logins/Disable Certain Features

Turn Site to "Read Only"

Turn Site to Single "Maintenance Mode" page.

Doing any of the above is pretty trivial. You can throw a particular "flag" in an .ini file, or add a row/value to a site_options table in your database and just read that value and do the appropriate thing.

But these solutions have their problems.

Disadvantages/Problems

For instance, if you use a file for your application, and you want to switch off a certain feature temporarily, then you need to update this file on all servers.  So then you might want to look at running something like ZooKeeper, but you are probably overcomplicating things.

So then, you might decide that you want to store these "feature" flags in a database. But then you are obviously adding unncessary queries to each page request. So you think to yourself, that you will throw memcached in to the mix and just cache the query. Then you just retrieve all of your "Features" from memcached and add a 2ms~ latency to your application on every page. So to get around this, you decide to use a two tier-cache system, whereby you use an inmemory cache on each machine, (like Apc/Redis etc). This would work, but then it gets complicated, because you would have to set the key/hash life to perhaps 60 seconds, so that when you purge/invalidate the memcached object storing your "Features" result, your on machine cache is prompt enough to get the the new states.

What suggestions might you have? Keeping in mind that optimization/efficiency is the priority here.

答:
Instead of fetching config data from the DB upon every request, store it in memory (in c# use a static variable or the cache object or something) - then when you need to update a config value, update it in the DB. Then have a protected URL on each server that you can hit that forces the app to reload the config data. Then you could even write a front-end for updating server config data that also hits those URLs.

Or if you're in ASP.NET land you could just use the cache object and check out SqlCacheDependency.

Title: Solutions for "Maintenance Mode"


问:
OOP when using a GUI Designer
I usually do database and web development but at the moment I'm learning desktop development with Mono and Gtk# using using the MonoDevelop IDE. I'm also using the Stetic GUI Designer inside MonoDevelop to create the GUI.

What are the best practices when using a GUI designer to encapsulate extra logic that is related to a widget used in the GUI designer?

For example I may use a TreeView widget but I'll also need to have logic specific to how the cells render, deleting selections of rows, etc. My first thought would be to simply extend the Treeview like so:

```<code>public class MyTreeView : TreeView {}
</code>```

But I don't think I can do that and still use the GUI Designer (correct me if I'm wrong).

What I'm doing now is making a class that has the TreeView as a member of it:

```<code>public class MyTreeView
{
    private widget;

    private MyTreeView(TreeView treeView)
    {
        this.widget = treeView;
    }
}
</code>```

Am I on the right track or is there some special and fancy pattern or C# language feature that I don't know of that I should be using instead?

答:
You have a few patterns you can follow with .NET development. This is coming from a WinForms background - I've not used GTK# although it's probable that the skills are transferable. Both methods you've discussed are acceptable but which is correct depends on what you're trying t achieve.

Derive a class and override the functionality you require. This is the choice to make when you want to override functionality of a well-designed control. For example, you might override the OnPaint to change how the control paints. How far you can go with deriving depends on how well designed the base control is. An example here could be overriding the ComboBox to draw an icon next to items.

Use a custom control if you want full management of the control. This particular type is for when you are implementing your own control and you don't want any extra functionality. For example, you might be making your own list view control from scratch.

Use a user control if you want to combine different controls into the one surface. For example, you might compartmentalize parts of a form using this method.

Title: OOP when using a GUI Designer


问:
Is there an optimal number of lines of code per function?
Functions are not only used to minimize duplication of code - they are also used to split up a long function into smaller ones to increase readability, as well as making the code self-commenting. Yet this gain is not directly inversely proportional to the number of LOCs per function or method; otherwise we would have tonnes of functions, all of which only contains a single line or two of code.

This lead me to wonder: Does there exist an optimal number of LOCs per function? If so, what is it, and does it deviate between languages?

答:
The answer is of course 42.

Important to note: No funcion may ever violate the SRP, or you have to face the spanisch inquisition.

A few hints how to reduce the ammount of lines:

Are there comments marking individual sections? Those sections should be functions.

Are there if-else chains or switch statements outside of a factory/builder? Your design may need some better design patterns to help you split responsibilities.

Are your functions easy to test? Make your functions easy to test, they will fall apart.

Is it complex and just no land in sigth (1000 line monsters)? Do scrap refactoring - that is refactor and don't save it in the hope to get educated about the codes responsibilities.


问:
What is the maximum value of index of an ArrayList?
I was thinking about it. You may have access to endless memory (one computer with lot of RAM) so that you can keep on adding more and more elements to your ArrayList.

But, I think that you can only access elements BY INDEX up to a certain value of index. The maximum size of this index could be = maximum number your computer can represent, that is long 9,223,372,036,854,775,807 in Java.

I know that you can access the NEXT element using an iterator. But, how do i access elements after the (9,223,372,036,854,775,807)TH index, using an index number ?

答:
ArrayList in Java has a get(int index) method.  int is a signed 32 bit value, with a maximum value of 2,147,483,647.  That is the largest possible value that can be accessed in an ArrayList.  Period.  The specifics of what the maximum size of the array or ArrayList differe based upon the implementation of the JVM (which may be lower than the MAX_INT value).    You can't make an ArrayList (or for that matter an int[] array) that has a long for its index.

If you were to try to instantiate an array list of this magnitude, you would have a structure that is at least 8 gigabytes - this only accounts for MAX_INT pointers, and not the additional space of the data at each point.

Attempting to access beyond the maximum value allowed through an iterator associated with the array would likely result in one of OutOfMemoryException, IndexOutOfBoundsException or a NoSuchElementException depending on implementation.

This is very impractical use of memory.  If one was to want such a data structure, one should investigate less RAM intensive approaches such as databases, sparse arrays, and the like.


问:
Using public final rather than private getters
I see most immutable POJOs written like this:

```<code>public class MyObject {
    private final String foo;
    private final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public String getFoo() {
        return foo;
    }

    public int getBar() {
        return bar;
    }
}
</code>```

Yet I tend to write them like this:

```<code>public class MyObject {
    public final String foo;
    public final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }
}
</code>```

Note the references are final, so the Object is still immutable.  It lets me write less code and allows shorter (by 5 chars: the get and ()) access.

The only disadvantage I can see is if you want to change the implementation of getFoo() down the road to do something crazy, you can't.  But realistically, this never happens because the Object is immutable; you can verify during instantiation, create immutable defensive copies during instantiation (see Guava's ImmutableList for example), and get the foo or bar objects ready for the get call.

Are there any disadvantages I'm missing?

EDIT

I suppose another disadvantage I'm missing is serialization libraries using reflection over methods starting with get or is, but that's a pretty terrible practice...

答: One possible disadvantage I can see offhand is that you're tied to the internal representation of the data in the class.  This probably isn't a huge deal, but if you use the setters, and you decide that foo and bar will be returned from some other class defined somewhere else, the classes consuming MyObject would not be required to change.  You would only need to touch MyObject.  However, if you use the naked values, then you would have to touch everywhere your MyObject i used.</p>


答:
Four disadvantages that I can think of:

If you want to have a read-only and mutable form of the same entity, a common pattern is to have an immutable class Entity that exposes only accessors with protected member variables, then create a MutableEntity which extends it and adds setters.  Your version prevents it.

The use of getters and setters adheres to the JavaBeans convention.  If you want to use your class as a bean in property-based technologies, like JSTL or EL, you need to expose public getters.

If you ever want to change the implementation to derive the values or look them up in the database, you'd have to refactor client code.  An accessor/mutator approach allows you to only change the implementation.

Least astonishment - when I see public instance variables, I immediately look for who may be mutating it and worry that I am opening pandora's box because encapsulation is lost.
http://en.wikipedia.org/wiki/Principle_of_least_astonishment

That said, your version is definitely more concise.  If this were a specialized class that is only used within a specific package (maybe package scope is a good idea here), then I may consider this for one-offs.  But I would not expose major API's like this.

Title: Using public final rather than private getters

Body:
I see most immutable POJOs written like this:

```<code>public class MyObject {
    private final String foo;
    private final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public String getFoo() {
        return foo;
    }

    public int getBar() {
        return bar;
    }
}
</code>```

Yet I tend to write them like this:

```<code>public class MyObject {
    public final String foo;
    public final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }
}
</code>```

Note the references are final, so the Object is still immutable.  It lets me write less code and allows shorter (by 5 chars: the get and ()) access.

The only disadvantage I can see is if you want to change the implementation of getFoo() down the road to do something crazy, you can't.  But realistically, this never happens because the Object is immutable; you can verify during instantiation, create immutable defensive copies during instantiation (see Guava's ImmutableList for example), and get the foo or bar objects ready for the get call.

Are there any disadvantages I'm missing?

EDIT

I suppose another disadvantage I'm missing is serialization libraries using reflection over methods starting with get or is, but that's a pretty terrible practice...


问:
How are operating systems compiled and booted the very first time?
I'm interested in how operating systems work. I've been reading some articles about Linux and seem to understand how it all generally comes together, but I feel like there's a chicken and egg dilemma when it comes to constructing an operating system.

Since Linux is written in C (and Assembly), which needs a compiler to be compiled, how does one actually compile an operating system for the first time? Do you first write a boot loader out of your existing OS? Or do you do something else? Do you have to dual-boot for the first time? Or you need two machines? What did Linus first end up with when he started his project? What did his very first result look like?

What's the very first thing you need to design and write when you're programming an Operating System?

答:
This happens all the time in embedded systems.  Generally you compile on an existing OS targetting whatever processor it is you are doing the OS for.   This code then needs to be put in a form that the processor can load, either in a EPROM, or you make  a "Bootloader"  which has the job of being the first thing the processor will execute then it will work out how to load the OS off a medium such as a harddrive.

On the PC architecture there is a "BIOS" which provides basic access to various hardware like screen and harddrives, etc.  It doest the "Bootloading" for you.  So most PC based OS's like linux and windows use this to get themselves going using a "Boot Sector" on something that provides a file system.

The simplest OS is often just a task scheduler (multi threading), and a simple hardware abstraction layer.  For the task schedule you will generally have a timer source that triggers a interrupt

```<code>void MyTaskSchedulerInterruptHandler()
{
   SaveStateOfCurrentTask(); // save all the CPU registers
   FindNextTaskToExecute();  // using tables of tasks currently being run,
                             //find one to run next
   ExecuteTask();  // load all the CPU registers for this task
   // return from interrupt will then make the CPU start on the loaded task
}

main()
{
    SetupInterruptVectors();
    InitializeHardware();
    StartSystemTasks();
   //never gets here
}
</code>```

OwnerDisplayName: Gleb

Body:
This happens all the time in embedded systems.  Generally you compile on an existing OS targetting whatever processor it is you are doing the OS for.   This code then needs to be put in a form that the processor can load, either in a EPROM, or you make  a "Bootloader"  which has the job of being the first thing the processor will execute then it will work out how to load the OS off a medium such as a harddrive.

On the PC architecture there is a "BIOS" which provides basic access to various hardware like screen and harddrives, etc.  It doest the "Bootloading" for you.  So most PC based OS's like linux and windows use this to get themselves going using a "Boot Sector" on something that provides a file system.

The simplest OS is often just a task scheduler (multi threading), and a simple hardware abstraction layer.  For the task schedule you will generally have a timer source that triggers a interrupt

void MyTaskSchedulerInterruptHandler()
{
   SaveStateOfCurrentTask(); // save all the CPU registers
   FindNextTaskToExecute();  // using tables of tasks currently being run,
                             //find one to run next
   ExecuteTask();  // load all the CPU registers for this task
   // return from interrupt will then make the CPU start on the loaded task
}

main()
{
    SetupInterruptVectors();
    InitializeHardware();
    StartSystemTasks();
   //never gets here
}

OwnerDisplayName: Keith Nicholas


问:
Is it a good idea to schedule regular time to clean up code?
I'm managing a small team of developers. Every so often we decide we're going to spend a day or two to clean up our code.

Would it be a good idea to schedule regular time, say 1 week every 2 months, to just cleaning up our codebase?

答:
I have my developers tidy their code prior to checkin (Subversion) or merging with the main development branch (Git).

I have them do the following:

Remove irrelevant comments

Ensure that their methods, arguments and variables are appropriately named

Make sure there is structure to their classes and items are encapsulated as they should be

Refactor to improve readability and to reduce any code smells

For the larger projects, the code is reviewed formally prior to merging from the development branch to the main branch.

I think that "devoting time" will mean it is something that might be deferred, or put off due to the amount of work involved. By having developers do it on a per-checkin (which equates to a change request / issue in JIRA) it is much more manageable.


答:
My personal opinion: It's absolutely required for 90% of projects.

Particularly for projects that are heavily driven by sales, there's usually a big push for including new features in every release, and you inevitably end up having to compromise your better instincts and introduce a few kludges / hacks here and there.

Eventually you've accrued enough 'technical debt' through these little compromises that you end up spending a fair amount of time working around the flaws in the code base, and are unable to use to it's full potential.

Usually there are two types of issues generated this way:

Small ones which can easily fixed but may be systemic, e.g. improperly named parameters,
incomplete error handling, etc. They typically will have little impact outside of the
block of code where they appear. The best way to deal with these it is code reviews and
checking the code as it's being written / modified. As others have stated, there's no
need to set aside a special refactor cycle to fix these errors.

Big ones which may have arisen from incomplete specifications or poor design decisions
early on, or two developers / teams creating two different solutions to the same
problem. These are generally much more difficult to fix and require a concerted effort
to fix. As a result they are usually deferred, until the become a perpetual nuisance.
These kinds of issues require a dedicated period of time to fix.

I generally try to reserve time for a pure refactorring / bug-fixing cycle every 3 to 4 cycles. I always ask my developers to tell me when they feel frustrated with the code base as well. Not every developer has to work on the clean-up effort - you can usually (but not always) stagger the teams a bit, so only one team is working on clean-up at any given time.

Title: Is it a good idea to schedule regular time to clean up code?

Body:
I'm managing a small team of developers. Every so often we decide we're going to spend a day or two to clean up our code.

Would it be a good idea to schedule regular time, say 1 week every 2 months, to just cleaning up our codebase?


答:
Not in my opinion. If you let too much time go between when you encounter tech debt and when you fix it, you lose context of what the problem is. It takes longer to fix, and it tends to get fixed worse. Most importantly, people leave the broken windows because it's not "clean up week".

Personally, I negotiate for technical debt cleanup each sprint if I know we created some in the sprint before. It keeps the debt fresh in people's minds. It limits the amount of code using the problem code so that refactoring is easier. It prevents technical debt from piling up. And it helps push developers from just slapping something together, because I'm just going to make them do it right next sprint (so might as well do it right in the first place).


问:
Writing an API that is syntactically valid in multiple programming languages
I'm planning to write a single API that is syntactically valid in most major programming languages (to the greatest extent possible, so that only minimal amounts of code will need to be re-written when moving from one language to another). I think the simplest way to do this would be to write a group of functions that consisted entirely of function calls and variable assignments, since the syntax for function calls is almost exactly the same in all major programming languages.

Of course, I'd need to write "wrapper" functions for if-statements and while-loops, since the syntax of each of these is different in each programming language.

Here's a proof-of-concept for one "polyglot" function that should work in most programming languages:

```<code>//JavaScript syntax
function proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}

//Java syntax
public static void proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}

//Python syntax
def proofOfConcept():
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.

//C syntax
void proofOfConcept(){
    printSomething("This is just a proof of concept."); //the function printSomething will
    //                      need to be implemented separately in each programming language.
}
</code>```

Would this be a useful design strategy, or is there a better way to do this? I think this would be a useful strategy for developing libraries in multiple programming languages, althogh it would require a small number of "language-specific" functions to be written for each target language.

答:
First question - is it useful?  Not particularly.  Trying to make one API that fits a multitude of languages is often a mistaken approach.  There are several different programming types listed in the example:

C - classic procedural programming

JavaScript - multi-paradigm tending to functional and object oriented

Java - Object Oriented.

Python - multi-paradigm tending to object oriented

The way of thinking in each of these languages is particular to that language. One can try to write procedural code in all the languages - completely ignoring polymorphism and just reverting everything to C like struts, but it would not integrate well with others.  It would also forgo all the advantages of writing in a higher level language.  Passing around dumb objects to static procedures defined somewhere - that is so 1980s.

The question of why really shows up.  What practical use would this serve? If I am writing C code, I'm writing C code.  Polyglot shops exist, but they are not the norm (it is much easier to hire 6 programmers for one language and get stuff done than it is to hire 1 programmer in each of 6 languages and get the same amount of stuff done).  Rarely does one find a programmer that is writing Java and C at the same time where the perceived advantage of having one library API that fits both Java and C could be of a very small advantage.

What you are talking about is implementing a domain specific language (the printSomething(String) of the polyglot API) as a runtime environment in a multiple languages. This isn't impossible, but isn't that useful either.  This is harder than one imagines - Python's scope is based on indentation, Javascript's semicolon is a statement separator as opposed to the statement terminator in Java and C (and non-existent in python).

This isn't an impossible task, but really, it isn't that useful.


问:
How should contributions to an open source project be managed by the owner(s)?
When managing an open source project (using a service like GitHub) how would one respond to the following:

Somebody has kindly submitted a patch to add a new feature or address a problem. Any one of the following situations occur:

The source code doesn't meet one or more naming conventions, etc.

I feel that the source code could be improved in a certain way. Perhaps the same effect can be achieved with far simpler source, or perhaps another useful feature would be needed.

Q1. Is it acceptable for me to alter the submitted source? (is this possible on GitHub?)

Q2. Should all such submissions be rejected in accordance with submission guidelines?

Q3. If yes to Q2, what about a really neat idea that was poorly implemented? Is it acceptable for me to just go ahead and create my own?

I want to encourage contribution but at the same time it is important to maintain a certain standard.

答:
If there aren't too many contributors, and this contribution is fairly valuable, you could accept the patch as is, and then, in the next commit, rewrite parts of it yourself, or reformat it to confirm to the coding standards. — Then, afterwards, you'd send an email to the contributor, with a link to a diff of the changes you made. Hopefully the contributor will then study the diff, and submit a better patch the next time, which you don't need to amend.

This might be a good idea, if you have not yet written any Contributors Guide or Coding Style documents. In fact, you could continue in this manner (accept and amend patches, email back links to diffs) for a while, until you've noticed what mistakes most contributors do. And then you include only those mistakes in a  Contributors Guide and a Styling Guide.

If you do things in this manner, answers to Q1-Q3 would be:

Q1: Yes, edit the submission, in a subsequent commit

Q2: Not applicable (I've assumed you have not yet written any guidelines)

Q3: Say thanks and rewrite it :-)  (Perhaps it's pointless to apply a patch at all, if, in the next commit, you rewrite it completely anyway)


问:
Is LINQ to SQL dead?
Is there any reason to keep using Linq to SQL, or is it better to move to ORM techniques like EF, NHibernate etc.

We are using Linq to SQL in a new large enterprise application that will exist for a long time. The motivation for this new enterprise application is that the application was ordinary written in Visual Basic and since Microsoft stopped the support we where forced to rewrite the application. It’s seems that we are already there but this time with our DAL (Data Access Layer).

I have already read this article, but it only compare to EF's weakness.

答:
more stable than dead imho:

http://www.thinqlinq.com/default/LINQ-to-SQL-enhancements-for-2010.aspx

http://jonkruger.com/blog/2009/06/06/linq-to-sql-is-not-dead/

They have shifted their improvement effort over to Entity Framework where it is really needed if that product is to succeed.  Expect nothing new but compatibility and bug fix on linq2sql for a while.

This site is run with a whole lot of linq2sql if I am not mistaken.

Title: Is LINQ to SQL dead?


答:
No.

Fix it while you're working on it:

If you wait to refactor the bit you're working on, you'll forget a lot about it, and have to spend time to get familiar with it again.

You won't end up "gold-plating" code that ends up never being used because requirements changed


答:
It is not that clear if you meant an additional clean-the-code exercise once in a while. In that sense , yes.  What ever practices we follow, some degradation always occur.  </p>

<p>You should not use that as excuse not to do the right thing [Applying SOLID principles, relevant unit tests, inspections etc  ] in the first place.  </p>

Body:
It is not that clear if you meant an additional clean-the-code exercise once in a while. In that sense , yes.  What ever practices we follow, some degradation always occur.

You should not use that as excuse not to do the right thing [Applying SOLID principles, relevant unit tests, inspections etc  ] in the first place.


答:
For normal arrays, if you are using the stock Oracle JVM, it seems that the actual answer is MAX_INT-5 or MAX_INT-2 depending on version.

For ArrayList the answer seems to be MAX_INT-8.  (Line 191, as the source code apparently has no anchors to link to!)

Title: What is the maximum value of index of an ArrayList?

Body:
I was thinking about it. You may have access to endless memory (one computer with lot of RAM) so that you can keep on adding more and more elements to your ArrayList.

But, I think that you can only access elements BY INDEX up to a certain value of index. The maximum size of this index could be = maximum number your computer can represent, that is long 9,223,372,036,854,775,807 in Java.

I know that you can access the NEXT element using an iterator. But, how do i access elements after the (9,223,372,036,854,775,807)TH index, using an index number ?


问:
Application Settings, Status and more as Singleton?
I am relatively new to programming (1yr field experience now) and I think that I am overusing the singleton pattern and I need some input on how to do it in a better way. Right now I am using singletons as an excuse for static global data. I use singleton for Application Status, Application Settings and also a lot for "Managers". Basically they are all objects which are needed by different parts of my application. I think this pattern makes it easier then creating one object and inject it into all parts that need this.

Any downsides to this approach?
Any suggestion regarding this matter?

答:
Sounds like a typical case of Singleton abuse. It's really easy to not think about separating responsibilities properly, it's much easier to just stick everything to global data. This is exactly why Singleton has bad reputation, it allows giving a cool name to bad practices.

It is hard to give any exact advice without knowing more about your application. You mention Application Status and Settings. From my experience these are usually a mixed bag of miscellaneous data that are not related to each other. If this is the case, then injecting the big Status/etc. class to every other class isn't much of an improvement compared to Singleton.  What you need to do is break up the big class. Depending how large your code base is, this can be really difficult, because global data can cause everything to be dependent of everything.


问:
What changes are too big to be made easy by proper design?
This is a rather vague question, but it's something I've never felt has been answered in a satisfactory way when reading about proper design.

Generally, when learning about Object Oriented programming, abstraction, factoring out, etc, the holy grail of design - and the reason they always claim you're using the development techniques in question - is that it will make your program "easy to change", "maintainable", "flexible", or any of the synonyms used to express such a productive-sounding concept.  By marking ivars private, splitting code up into many small, self-contained methods, keeping interfaces general, you supposedly gain the ability to modify your program with total ease and grace.

For relatively small changes, this has worked well for me.  Changes to internal data structures used by a class to increase performance has never been a major difficulty, and neither have changes to the user-interface end, independent of the API, such as redesigning a text entry system or overhauling the graphics for a gameplay element.

All of these changes seem inherently self-contained.  None of them involve any changes to the behavior or design of the component of your program being modified, as far as outside code it concerned.  Whether or not you're writing procedurally or in an OO style, with large functions or small, these are easy changes to make even if you have only a moderately good design.

However, whenever the changes become big and hairy - that is, changes to the API - none of my precious "patterns" ever come to the rescue.  The big change remains big, the affected code remains affected, and many hours of bug-spawning work lie ahead of me.

So, my question is this.  How big a change does proper design claim to be able to facilitate?  Is there some further design technique, either unknown to me or that I have failed to implement, that truly does make sticky-sounding modification simple, or is that promise (which I have heard made by so many different paradigms) merely a nice idea, completely disconnected from the immutable truths of software development?  Is there a "change tool" I can add to my toolbelt?

Specifically, the problem I am facing that's led me to the forums is this:  I've been working on implementing an interpreted programming language (implemented in D, but that's not relevant), and I've decided that my closures' arguments should be keyword-based, rather than positional as they currently are.  This requires modifying all existing code that calls anonymous functions, which, luckily, is rather small because I am early on in the development of my language (< 2000 lines), but would be enormous if I had made this decision at a later stage.  In such a situation, is there any way that by proper foresight in design I could have made this modification easier, or are certain (most) changes intrinsically far-reaching?  I'm curious if this is in any way a failure of my own design skills - if it is, I'd be very eager to improve them with the necessary reading material if there is a way to ameliorate the severity of the problem.

To be clear, I am in no way skeptical of OOP or any of the other patterns commonly in use. For me, however, their virtues are in the original writing, rather than the maintaining, of code bases.  Inheritance allows you to abstract repetitive patterns out well, polymorphism allows you to separate code by human-understood function (which class) rather than by machine-understood effect (which branch of the switch statement), and small, self-contained functions allow you to write in a very pleasant "bottom-up" style.  However, I'm skeptical of their claims of flexibility.

答:
Since design is intended to take a development project from zero blank-sheet nothing to a working reliable final product (at least the design for one), and that is the biggest change to a project there can be, I doubt there's such a thing as a change too big to handle.

If anything it is the reverse. Some changes are too small to bother with any "design" or fancy thinking.  Simple bug fixes, for example.

Remember that design patterns are to help think clearly and find good design solutions to common situations, like creating huge numbers of small identical-type objects.  No list of patterns is complete.  You, and all the rest of us, will have design problems that aren't common, that won't fit any pigeon-hole.  Attempts to make every little move in a software development process according to one official pattern or another, is an overly religious way to do things, and leads to unmaintainable messes.

All work in software is naturally bug-spawning. Football players get injuries. Musicians get calluses or lip spasms depending on their instrument. (If you get lip spasms while playing guitar, you're doing it wrong.)  Software developers get bugs.  We love to find ways to reduce their spawning rate, but it'll never be zero.