问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
There are some fairly decent array functions in PHP, providing list processing capacity, with callbacks and create_function() providing a basic lambda calculus.

The main problem with it, is that it is far too verbose in PHP, a shorthand system would be excellent, particularly where the map/reduce commands are concerned.

More importantly, the list functions are not entirely complete:

there is no foldr function, array_reduce() provides foldl

array_map() should pass the key in the second argument, as array_walk() does

an array_map_keys() could be useful for key modification

list comprehension is very clunky, range(), array_fill() and array_fill_keys() only handle so many cases, and array_filter() is separate

I'm not aiming to make PHP in to Haskell, but PHP is often used for list type data structure manipulation and having a full set of tools in this regard would be useful.


问:
Report to capture scope creep in iteration
I am looking for a report to capture the "Scope Creep" within an iteration.  We are using Scrum on TFS 2013 on premise.

We are constantly asked by management to bring work into an iteration, but are still pressured to meet the commitments made in the planning meetings.  Unfortunately it happens often enough that it isn't a matter of manually tracking 1 or 2 work items per iteration.

Also sometimes we have just underestimated work and it takes longer than we had planned.

I would like to pull a report from TFS or the warehouse/cube which shows when work is brought into an iteration (i.e. new PBI/Bug added) or work on an existing item increases.

I would like to use this report to show management the impacts of bringing in unplanned work and/or use the report as data to improve our estimates.

答:
The official Agile answer is that this simply should not be allowed.  Unfortunately, as you are experiencing, the reality is that this often happens.  Sometimes this is because business requirements change too rapidly even for short sprints.  Sometimes this happens because of pure bad planning on the part of the product owner.  And unfortunately sometimes this happens because management has not truly bought in to agile and therefore feels they have the right to tell you to do whatever task whenever.  This last case is the hardest to deal with.

First, when accepting a new story into a sprint, it should be pointed just like any other story.  All work should be tracked regardless of whether it was added to the sprint the right way (in planning) or the wrong way (at random during the sprint.)  You should know your velocity.  You should now how many points you agreed to do in planning.  If you point new stories, you should be able to tell exactly how many extra points you are required to do.  You can therefore report during each sprint how many points over your velocity you were asked to do.  At the end of each sprint, you can therefore show that you were late on X,Y,Z because you were asked to do new stories with numbers of points that put you over your velocity.

The second thing you can do is to track how many points of properly planned-at-the-start stories you are able to complete and use that as your velocity when planning.  Be very transparent about this.  Make it clear to management that you are unable to take as many stories as you otherwise would because you are being forced to do extra, unexpected work.

It is an unfortunate truth that for this to work, you will have to stand up to management and explain that in order for agile to work, agile rules must be followed.  This can be hard or impossible to do if management is poor.  But it must be clearly explained each time stories are added mid-sprint that you can't get the benefits of agile without following the rules of agile, and avoiding mid-sprint work is one of the most important ones.

ContentLicense: CC BY-SA 3.0


问:
Why does a proportional controller have a steady state error?
I've read about feedback loops, how much this steady state error is for a given gain and what to do to remove this steady state error (add integral and/or derivative gains to the controller), but I don't understand at all why this steady state error occurs in the first place.

If I understand how a proportional control works correctly, the output is equal to the current output plus the error, multiplied by the proportional gain (Kp).  However, wouldn't the error slowly diminish over time as it is added (reaching 0 at infinite time), not have a steady state error?  From my confusion, it seems I'm completely misunderstanding how it works - a proper explanation of how this steady state error eventuates would be fantastic.

答:
Consider the following system: (source: prenhall.com)

This is a proportional system with a plant G(s), gain K, input R(s) and output Y(s).  The system has no disturbance modeled and has unit feedback, but using this we can show how the proportional controller (even in this simplified, ideal state) inherently produces an offset at the output.

Let's express our output Y(s) in terms of everything else.

Y(s) = G(s) * K * (X(s) - Y(s))

Doing a few manipulations, you can get this:

Y(s) = X(s) * [G(s)*K/(1+G(s)*K)]

What this means is Y(s) is always proportional to the input signal X(s) multiplied by the system G(s)*K/(1+G(s)*K), which means there is always a biased output (unless K or G(s) go to infinity).


问:
How to avoid big class complexity while keeping encapsulation?
I'm developing a PHP library to work with big numbers (at this moment only with a "Decimal" class, but I want to add new classes, to handle Integers, Rationals, and Complex numbers). In any case, the problem is the following:

On one hand, PHP hasn't method overloading. I can use "magic methods", but I want to keep type hinting in method signatures. Even if I have a common interface, every number type deserves specific handling because its internals will be completely different, so finally it appears as a natural idea to add type-specific methods to allow interoperability between those classes (Decimal, Integer, Rational...).

On the other hand, there are virtually infinite functions that someone may want to apply to a number. Currently, I'm implementing many of such functions in every class to directly handle the internal properties and avoiding the creation and destruction of intermediate objects (a good example is the sin, exp or cos computing, because they have a lot of intermediate computations).

Then, keeping type specific methods increases the class complexity, and keeping the function methods in the number classes also increases the class complexity.

The problem is that I don't have any good idea about how to extract the function algorithms outside the "number classes" without loosing much performance and without violating the properties encapsulation.

Anyone knows a "good" pattern to follow?

Important to note: I think the problem is not trivial mainly because numbers aren't well handled in a hierarchical way, there are a lot of overlappings between number sets, and using interfaces isn't enough (see this question about "self-types" to see why i say that). I don't want a "perfect" solution, but one good enough that allows me to design a good library for theory purposes, not only for numerical computing.

The case: imagine a class that represents a number, call it Number . Suppose that, in addition to basic arithmetic operations, you have a lot of one-variable functions: sin, cos, tan, arcsin, arccos, arctan, exp, logarithm, square root, gamma, riesz, airy's function, and so on... and add to it many other two-variable functions, and maybe even more complicated functions (with theoretical applications, not randomly defined) with 3 or more variables.

One possibility is to extract the algorithms to compute such functions to other classes in order to keep the class size under control. The problem of this approach is that then you have to expose the internals number classes if you want performance, or loosing a lot of performance if you want to respect SOLID.

I have three points that I want to control: classes size (to improve readability), SOLID principles (because the library has to grow a lot and ensure quality and testability), computation performance (because the library's purpose is to be useful, not a toy).

Proposed Idea:

Finally I've arrived to the conclusion that I should abstract the functions using specific (and instanciable) classes. This will allow me to implement new interesting features like function composition, second order functions, computing limits, integrals and differentiations in a symbolic way... That's a lot of work, but in first place I'll implement only the pillars to make it possible.

Functions will work in first place directly with number objects, and where it's worth I'll add a custom inner representation to boost the performance. Translating the object to the function's inner representation will add some overhead, but less than creating and destructing Number intermediate instances (or I think so, I'll benchmark this type of changes to ensure the complexity increase it's not a waste of time and code lines).

Since PHP don't have parametric classes, part of the contract will be checked at runtime with specific methods, if possible at "function-construction time" rather than at "function-evaluation time". For example, I'm thinking on adding two getters to obtain the return type and the argument "types" ¹ and n-arity. About the second mentioned getter, this will be only for "corner cases", since I prefer to subclass and add a specific and hinted method.

Here I use the word types, but I'm referring to number sets, it's not the same even it seems so. The addition of Function classes and instances allow me to create type-specific methods without having to worry about class size (the number of methods will be small even if I have type-specific methods).

答:
You are way too much worrying about performance without actually having measured it.

Let your Number class just be a facade, and delegate each computational function to a internal helper class on its own, like a SquareRootCalculator, a SinCalculator, and so on. If you are really going to implement that calculations right from the ground, each of it is complex enough to justify a class on its own. Delegation has typically only a neglectable performance impact, so unless you this becomes a real, measurable problem, just try it out.

Moreover, since you wrote "the library's purpose is to be useful, not a toy" - did you consider to use some of the already existing PHP libraries for big numbers or complex numbers? Or if there is none which suits your needs, did you consider to encapsulate one an older, mature library written in C for this task (I am sure there are some very good and very fast libraries available for free)? That would not only prevent your PHP classes from becoming too complex, but also prevent you from reinventing the wheel.


问:
Is JavaScript fail-safe?
I was compiling a list of comparison of top 10 programming languages (JavaScript included). I was doing it from this Wikipedia page.

However, in the third table (Failsafe I/O), there is no row for JavaScript. I find it a bit weird because JavaScript is included in the first two comparisons (General comparison and Type Systems).

So my question is, is JavaScript fail-safe? If Yes, what would the row for JavaScript in the fail-safe I/O table look like?

答:
It depends on what kind of I/O you're after. I think that table is primarily looking at system calls, and the stdin/stdout interface to a console windows or terminal. System calls simply don't exist in Javascript, and there's no stdin/stdout-style console window either, so I assume that's why it's not listed (though you can make a case for node.js here).

The closest thing I know of to failsafe-ness in vanilla Javascript is that calling a function that doesn't exist or accessing a resource that hasn't been loaded will throw an exception. But everything that is available generally "just works" without any error codes or exceptions. Assigning text to innerHTML or using HTML5 canvas methods won't throw if the browser "fails to render" the result somehow (at least, if it does, that's not documented/standardized behavior). Also note that Javascript has no (cross-browser) filesystem API, which is the one thing I can think of where error codes/exceptions would effectively be mandatory. And, Javascript's closest equivalent to console I/O--the console.log() function--also isn't standard, meaning you're never supposed to use it in production code anyway.

So as far as I can tell, the sort of "I/O" where "failsafe" is a meaningful property to ask about doesn't really exist in Javascript. Simply leaving it out of the table probably was the best way to represent it.

Title: Is JavaScript fail-safe?


答:
Javascript is indeed a fail-safe language, since it also raises exceptions in case of an error (like Java or Python). However, the specific language is not included in this list, because this list refers to fail-safe programming languages taking into account the occasions of errors in I/O operations and system calls. Javascript has been a client-side programming language for various years, so I/O and system calls are were out of scope in this language.

However, with the prevalence of Node JS, which is a server-side implementation of Javascript, I think this language should be included in this list from now on.

Title: Is JavaScript fail-safe?

Body:
I was compiling a list of comparison of top 10 programming languages (JavaScript included). I was doing it from this Wikipedia page.

However, in the third table (Failsafe I/O), there is no row for JavaScript. I find it a bit weird because JavaScript is included in the first two comparisons (General comparison and Type Systems).

So my question is, is JavaScript fail-safe? If Yes, what would the row for JavaScript in the fail-safe I/O table look like?


问:
Deciding factors in pair programming
Are there specific things that you look out for before getting the team into pair programming? Obviously pairing someone who's great with C++ with another who knows ASP.NET best won't get me far, but how about someone who's great with C++ with another who knows Java best but can pick up C++ quick enough? </p>

<p>What else? Experience levels? Character traits? </p>

答:
I've found pair programming very useful for learning/teaching. But don't put a guru with a newbie, the newbie will be overwhelmed and the guru annoyed. You should have one person who knows a bit more than the other, or two persons that know different things. In that case pair programming is a very efficient way of transferring the skill set.

It is IMO least useful when two programmers have worked so much together that they would solve a problem in exactly the same way if they did it separately. Then you are wasting one persons time.

ContentLicense: CC BY-SA 2.5

Title: Deciding factors in pair programming


问:
Best OOP practice for object vs dataservice
I am working on a new project and am curious as to how I should go about doing something properly.

Lets say I have a table called "leads" in my database. This clearly means that a single "lead" would be an object, and I'd need a class in order to create, update, or pull information for said "lead" object.

Now here is where my question comes in. Lets say I have a page called leads.php with a table that I want to populate with multiple "leads" from my database. Do I create the method for listing all leads within the "lead" class itself, or do I create a seperate "data service" class, which would represent a service object used to retrieve multiple leads?

Any help would be greatly appreciated.

答:
If you add a method Lead.list() where it returns a list of leads it's violation of SRP, as the fetching a list of Leads is not the responsibility of Lead object.

So the best option is to use a data service or a repository. For example LeadRepository could have methods GetAll(), GetById(id)


问:
Is lazy loading always required?
I know lazy loading is required when an expensive database call is being made. It would make sense using lazy loading in this example. The below example is in the context of asp.net so it's thread safe.

```<code>private list<Customer> _AllCustomers;
public list<Customer> AllCustomers {
get {
    if (_AllCustomers == null) {
        _AllCustomers = ExpensiveDataCall();
    }

    return _Customers;
}
 }
</code>```

Even if it's just instantiating an object that is used in multiple places, I always use lazy loading. Consider the following example:

```<code>private _Customer;
public Customer Customer {
get {
    if (_Customer == null) {
        _Customer = new Customer;
    }

    return _Customer;
}
 }
</code>```

Recently someone told me that lazy loading is only required for expensive database calls. Is that right? I thought every time an object is instantiated memory increases(apologize for the terminology. I don't have lot of technical knowledge.)

答:
IMHO Lazy loading is a pattern in your list of design choices. There is no "always" or "never" .. more the question: when should I and when shouldn't I.

Way back when I used to always have lazy loading for most things, these days I rarely use it, preferring instead to load "a good amount" (more formally known as a "bounded context") of several objects and their associated collected (eg Invoice and its line items) would be suitable for a single "big load" without any lazy loading being used.

That said if I'm building a parts system for an aircraft I may choose to lazy load sub assemblies if the user decided they need to "drill down further" into what I have presented them on the screen rather than wait for all 100,000 parts to come back before the user can do anything.

Which brings me to my "rules of thumb".

If I'm going to show a screen (or page) of data to the user when they load up, then I do a "single big grab".

If the screen enables drill down (like a tree view or scrolling list) then I will load what is visible + 1 level / screen so the user has some "play" when they start to scroll or start to drill down. The next block I will lazy load when I think the user has either directly asked for or has got "close enough" that they are about to ask for it.

The basic idea is that on average you should load as much data as possible without the user noticing that they are waiting for data to load (<1 sec is ideal).

When a user isn't involved then your consideration becomes "overall processing time" for a batch from source (database) > loading > processing > end result > final resulting storage or action. You want to load as much as

In your example:

Loading every customer for a small business system is probably ok (<100 or so) to take the hit and do it upfront, otherwise I would lazy load.

Loading and individual customer, assuming there is a good chance it is going to be used by the screen/process, I would do it upfront because transfer across the wire twice is likely to be more of a time lag than loading the customer along with other stuff on the server.

Your question: "does it consume memory"

Answer: Yes it does, every variable you use consumes some (usually not much) memory.

Better questions to ask:

do you care about the amount of memory it is taking up MORE than having the information available for the user without lag?

Answer: the larger the amount of "stuff" being loaded the more likely you are to use lazy loading.

what is the time delay involved in doing the lazy loading and is it done at a point where the user cares about the time?

Answer: by example If you show the user something first like the header or summary details and then you lazy load in all of the detail results the user doesn't usually mind waiting.
If your lazy loading in every last object then the user is waiting for the Customer record +  the specific invoice they care about + the total of their account + the transaction records + the line items for the invoice then you would likely choose to forward load Customer + Specific Invoice + Total of their account and then lazy load the transaction records ... the invoice line items would be a call based on your use case as to your needing to lazy load or advance load.

what are the costs (memory, lag time, network and database usage) associated with a "load"?

Answer: It depends. Everything on 1 machine, probably doesn't matter much, number of hits to the database will likely be your bottleneck. Client/server its probably time frame of the database query, web server is more likely network transfer followed by database that is the issue. Each one will move the goal posts as to where the costs are that you actually need to worry about.

Title: Is lazy loading always required?


问:
Data Storage patterns for intermediate saving a web-based workflow form
Background: I am developing a wizard based web form where users can log in an fill in some details and press next and previous to go back and forth in the wizard before they actually submit. When the user submits I would make a service call that performs some processing on the data.

Issue: Not all data is available readily to the user, and the user may choose to “save” the data instead of “submitting” it, and then come back (if s/he chooses to) and finish it later. This intermediate data would be incomplete (and in some cases invalid) - but for convenience we would let the user save it.

Solutions I seen in the past: In the past I have dealt with this with 2 distinct solutions -

Save the intermediate data in the regular tables (where submitted data is saved) and mark that data as “inactive”. The data would be "activate"d only when the user clicks submit and all data is valid. This involves modifying the service that is called on submit to accept the data on save the intermediate and invalid data. Also this puts the burden on the team to remember to check for “active” flag in every query.

The other option is to storing the intermediate saved data in huge denormalized CLOBs. The data could be structured within the CLOBs as an XML or JSON. The intermediate data (saved) is completely disjoint from the completed (submitted). The downside here is that now the form needs to be able to work with 2 different sets of services based on the status of the workflow cycle (if in-progress read the XML from the CLOB – if completed read from the service that has valid data!)

Question:
Is there a better way to solve this problem since it does seem like a universal issue in the enterprise world at least? Could someone point me to any data or storage “patterns” that the community has been following to solve this storage issue in web workflows?

Note:
The underlying database technology can be thought of a system that supports tables and individual fields can contain very large strings like CLOBs.

答:
Since you are designing a web site, there are multiple options and the selection is clearly depends on your requirement.

Save in client side

you could use cookies or local storage to achieve this, main advantage of this is you don't have to send and retrieve data back and forth to the server to persist.

However you won't be able to resume your work from the another client.

Save in server side

Persisting the data in the same tables and mark them as inactive will result in piling up invalid data in the system when user decides to abandon the workflow. But again this can be eliminated if the user is forced to continue or to cancel half completed workflow when the user attempt to use the workflow. One of the advantages in this one is it would be prone to less number of persistence errors as it's already in the database. However this may not work depending on the database design.

Saving the data as XML or JSON format on the server requires additional logic, and depending on the workflow it could be complicated to implement (such as conversion from the XML/JSON to domain model).


答: JavaScript does not have any I/O at all, and thus the question whether or not it is "failsafe" doesn't make sense.

Title: Is JavaScript fail-safe?


问:
Image segmentation - show or hide clusters
I'm trying to make a small program in c#, that will downsample image to specified amount of colors (using K-means). Then, user will be able to hide\show colored areas(clusters) in image. I've implemented image clustering algorithm and I also have info about main colors, but how to implement show/hide color function? Example below

for this moment program only simplifies image (in this example 5 colors)

this is what I want to have

答:
This function returns image only with selected colors.
List colors -list with selected Colors that are converted to int value with ToArgb() function (for better comparing).
LockBitmap class you can find here: http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp

public static Bitmap ReDraw(Bitmap bmp, List<int> colors)
{
    LockBitmap lockBitmap = new LockBitmap(bmp);
    lockBitmap.LockBits();

    for (int y = 0; y < lockBitmap.Height; y++)
    {
        for (int x = 0; x < lockBitmap.Width; x++)
        {
            int color = lockBitmap.GetPixel(x, y).ToArgb();
            bool flag = colors.Contains(color);
            if (!flag)
            {
                lockBitmap.SetPixel(x, y, Color.White);
            }
        }
    }
    lockBitmap.UnlockBits();
    return bmp;
}
```


问:
Property based testing without reimplementing the code under test
Given a very simple method such as:

```<code>  def squaredDistance(p1: Point, p2: Point) =
    math.pow(p1.lon - p2.lon, 2.0) + math.pow(p1.lat - p2.lat, 2.0)
</code>```

What are some valuable property-based tests that don't simply reimplement the method?

I can only think of testing for result >= 0.0, which is pretty broad.

答:
In general, your tests should normally not reimplement the code under test. This can happen to you with traditional tests as well. In fact, from my experience, property-based testing tends to be better for avoiding re-implementations.

When you think about the properties, you specifically do not think about implementation details (i.e. do not think about how you come to some result/property, but instead consider the result/property itself).

Property-based testing is particularly useful for mathematical properties. A square distance function, being quite well-founded in mathematics, is therefore a good match. Nevertheless, it takes a lot of experience. If you have a solid background in mathematics and/or predicate logic, it is so much simpler to find good properties. If all you know is traditional fixed input vs expected output testing, then you are in for a steep learning curve.

So let's look at the function in question a little bit closer. We do have something that works based on Point, so we will need a generator for that - I assume for this answer, that you got that covered already. The resulting value, according to your type signature, is a Double.

First off, property-based tests help you stamp down sub-optimal types. In particular, we know that squared distances always have to be non-negative. A 'Double' doesn't cover that information yet. So there's your first property that you get for free -> limit the result type to more closely resemble the mathematical result domain of the function.

Next, you can look at classical mathematics to find out general relations available for functions/properties and you will come across terms like "(anti-)symmetry" or "transitivity", all of which can be examined to check whether they should hold for your squared distance function. If they do, then you have yourself another well-defined property.

Let's say we add properties to ensure symmetry and transitivity, as well as non-negativeness. Next, you can look at numbers at the border of your domains and realize, that an output of 0 is something special and you add another property for the 0-distance being equivalent to being the same points.

Now you have 4 properties in place already. What I found in my experience of property-based testing is that you often need to make sure that you don't run into this problem: you have defined properties over your domain, but unfortunately, an implementation as simple as if (p1==p2) 0 else 1 satisfies all four properties.

Why is that? Because all our properties so far concentrated on the input. The output domain of the function is way under-defined still. One way to handle this would again be to add samples (input vs expected output), but can't we find a property for the output domain that does better?

In fact, some though (aka experience) tells you that when you generate a point, and then generate others, you could argue on the spread of distance values you'll get. You have to be careful to rule out equal points (due to the 0 distance) and the symmetry of distances. (for example, the distance from 0,0 to 1,0 and 0,1 is the same).

There are a lot of possible properties, but let's just make up one example: for each generated point, you use a normal int/double-generator to generate more points that differ in only one coordinate (for example, you start with (3, 15) and generate (3, 4) (3,7), (3,20), ...). When you remove duplicates form these and check the distance from your fixed point (3,15) to all the other (unique!) points, then you know that the distances/results must also be unique. So spoken in a more code-like fashion, you create a set of these other points, not including the fixed point, then calculate the distances for each of these to the fixed point and add the results to another set. Finally, you verify the sets are of equal size. I highly doubt, that your implementation code looks even remotely similar to that.

If you want to be safer, you could add two properties, one per axis (tuple-arity, whatever you want to call it). By adding these properties that essentially describe your output domain as opposed to your input domain, you immediately make it very hard for any hard-coded implementations like the example given above to still succeed.

However, and this is a major point of property-based testing, none of these six properties I have discussed so far guarantee that the actual results of your function resemble the square distance between numbers! So in my experience, you still need a few fixed input vs expected output tests in addition. The cool thing though, is that you can actually get away from your previous preconception that you even need a square distance. Once you start thinking about the actual properties of your functions, you often realize that the even being a "square distance" is nothing than an unimportant implementation detail that you might not even need to care about. So do you just want to have a distance function, or does it matter whether it's squared, euclidean, or something else entirely?

In my experience, if you need to limit it down to the exact function, you need to add in some fixed input vs expected output tests, as the properties in their generality provide still too much freedom. Happy to hear if there's another practical way to deal with this, but as usual, I'm just not seeing a silver bullet here.


问:
Render order of two-edge directed node graphs
I'm trying to find an algorithm for graphs with the following contents:

Nodes with no edges leading out of them (shown here as a red circle)

All other nodes have exactly two edges leading out (shown here as green diamonds)

I need to render these graphs a specific way:

Each circle has a known position.

Each diamond's position is determined by the positions of the nodes it is connected to.

The data is arranged as shown, but to be clear

```<code>CircleNode : { Position }
DiamondNode : { NodeA, NodeB, Position = Route(NodeA, NodeB) }
Graph : { CircleNodes, DiamondNodes }
</code>```

My solution works for most of the graphs I've constructed, but the more complex graphs I have overflow the stack long before they converge. I think I can use most of my existing code if I provide the nodes in depth last order - circles, then nearest diamonds, then next nearest to those, and so on. However, I'm not sure how to prove this will work for all graphs of this type.

What is this kind of problem called?

Is there a proven algorithm that can be applied?

Note: the diagrams above do not reflect the intended render layout, only how the data is represented in memory.

答:
1) about stack overflow - if your algorithm will stop, but graph is too large, use explicit stack (on heap) instead of recursion.
One way (not the only way) to prove that it will stop someday, is that size of problem is reduced EACH "round" and that "round" itself is limited by some constant.

2)
You didn't say how exactly should position of diamons be determined, so i will assume, that you want to node to be somewhere between nodes it connects to.

One way to do it would be something like simulated anealing:
place fixed nodes.
randomly place other nodes.
All nodes repulse other nodes (reduces with for example square of distance), nodes connected by edge are atracted (increases with square of distance).

Compute "forces" on all movable nodes. Move proportionaly to force and "time".

At first start with larger time, each step reduce it.

To get out of local minima, add random force (and reduce it with time).

After some iterations stablepositions for nodes will be found and there is chance it will be reasonable.


问:
No exceptions C++ and partially constructed objects
Looking over Joint Strike Fighter Air Vehicle C++ Coding Standard, rule AV 73 states something on the lines: Default c++ constructors should be avoided if that means leaving object in a partially constructed place. This is obvious a good advice but things get complicated when you also disallow exceptions (as it does)

I wonder if they also try to give something else in return to make it practical. E.g. following example needs 2 faze construction if OUT_OF_MEMORY has to be handled (but the problem is more general of course)

```<code>class A {
    A() = default; // no way to report construction of B and C
    int Init(); // allocation failure of B/C can be reported only here
    private:
    B* b;
    C* c
}
</code>```

One way to handle the problem is to have a A* Create() static member but in this case A has to free store allocated or keep an non-fully initialized state inside A and check it inside every member access, which seems not better at all than using a C style

```<code>int Initialize(A& out) // stack allocation
int Initialize(unique_ptr<A>& out) // free store allocation
</code>```

EDIT I posted one possible approach bellow also. I took under consideration that dynamic memory allocation is necessary and the fact that any errors can happen while fully constructing an object. This is a scenario that is plausible for any driver development work.

答:
Default c++ constructors should be avoided if that means leaving object in a partially constructed place. This is obvious a good advice but things get complicated when you also disallow exceptions (as it does)

Not necessarily. Consider these rules:

a constructor should receive already validated arguments, and perform no operations outside of initializations/movement of values (constructor's responsibility is to initialize the object, not to compute values, then initialize the object - that would break SRP).

if an object's construction is non-trivial, computational part should be moved into a factory function

Example implementation:

```<code>class A {
public:
    A() = deleted; // no way to construct instance that completely initializes A

    // int Init(); // don't use two-phased construction; it imposes on client code

    A(B* b, C* c) : b_{ b }, c_{ c } {}

private:
    B* b_;
    C* c_;
};

enum result { success, error };

// return error code
result make_A(B_and_Q_store& store, A*& instance)
{
    B * b = store.buy_a_b();
    C * c = store.get_q().make_a_c();
    if(!C)              // ERROR HANDLING
        return error;   // ERROR HANDLING
    instance = new A{ b, c };
    return success;
}
</code>```

Client code:

```<code>A* a = nullptr;
if(success == make_A(some_store, a)) // ERROR HANDLING
{
    // ...
}
</code>```

This implementation offers convenience and good design for client code:

make_A performs failable computations;

constructor contains only trivial code;

law of demeter is respected: because an instance of A only uses B and C, it shouldn't know (or depend on) how B and C are constructed (because it is no longer responsible for instantiating them).

Similar to what @rwong states (when he mentions side effects and validation), parameter/argument values are validated as necessary, before you create the A instance (that is, when you get to creating the instance, you already know all parameter values are valid).

Body:
Default c++ constructors should be avoided if that means leaving object in a partially constructed place. This is obvious a good advice but things get complicated when you also disallow exceptions (as it does)

Not necessarily. Consider these rules:

a constructor should receive already validated arguments, and perform no operations outside of initializations/movement of values (constructor's responsibility is to initialize the object, not to compute values, then initialize the object - that would break SRP).

if an object's construction is non-trivial, computational part should be moved into a factory function

Example implementation:

class A {
public:
    A() = deleted; // no way to construct instance that completely initializes A

    // int Init(); // don't use two-phased construction; it imposes on client code

    A(B* b, C* c) : b_{ b }, c_{ c } {}

private:
    B* b_;
    C* c_;
};

enum result { success, error };

// return error code
result make_A(B_and_Q_store& store, A*& instance)
{
    B * b = store.buy_a_b();
    C * c = store.get_q().make_a_c();
    if(!C)              // ERROR HANDLING
        return error;   // ERROR HANDLING
    instance = new A{ b, c };
    return success;
}

Client code:

A* a = nullptr;
if(success == make_A(some_store, a)) // ERROR HANDLING
{
    // ...
}

This implementation offers convenience and good design for client code:

make_A performs failable computations;

constructor contains only trivial code;

law of demeter is respected: because an instance of A only uses B and C, it shouldn't know (or depend on) how B and C are constructed (because it is no longer responsible for instantiating them).

Similar to what @rwong states (when he mentions side effects and validation), parameter/argument values are validated as necessary, before you create the A instance (that is, when you get to creating the instance, you already know all parameter values are valid).


问:
Shall i have to make my application code open source if using ejabberd?
I was looking into ejabberd and found it is licensed under GPLv2. Let's say that I am using it as follows:

You will come to my website/app and login, then start a chat using Instant messanger. I will use ejabbered on server side to handle and process your messaging and chating. Do I have to make my application code open source ?

答:
No, you don't need to open source your application.

You only need to open source a work derived from a GPL work when you distribute the work. But when your program runs your own server, you are not distributing it to your users. That means you do not need to license it to them. You can even modify the sourcecode. As long as the software doesn't leave your server, the sourcecode doesn't have to leave it either.

There is the AGPL which closes this loophole by requiring to sublicense the work to everyone who interacts with the software via a computer network, but the normal GPLv2 does not include this clause.

One thing web developers need to be aware of when they use GPL software is that the situation is different when you use GPL-licensed JavaScript, HTML or CSS code. When GPL-derived code is sent to and executed by the client, that code must also be licensed under GPL. But this is only a problem when you use GPL-licensed javascript. It is not a problem when your own JavaScript code is interacting with a GPL-licensed backend.


问:
Idiomatic C API with regards to pointers
I am trying to get a better understanding of how one would structure an API in C.

I create a struct Person

I have a init function that sets data on that struct

I have multiple "helper" functions that work on that struct

I'm wondering if the following code in C can be considered idiomatic from the point of view of more seasoned C developers.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct Person Person;

struct Person
{
    unsigned int age;
    unsigned int weight;
    Person *next_person;
};

void person_init(Person *p, unsigned int age, unsigned int weight, Person *next_person)
{
    p->age = age;
    p->weight = weight;
    p->next_person = next_person;
}

void person_print(Person *p)
{
    printf("person is %dy old\n", p->age);
    printf("person weight is %dkg\n", p->weight);
}

int main(void)
{
    Person p1, p2, p3, p4;
    Person *p_cur;

    person_init(&p1, 28, 80, &p2);
    person_print(&p1);

    person_init(&p2, 58, 93, &p3);
    person_print(&p2);

    person_init(&p3, 60, 60, &p4);
    person_print(&p3);

    person_init(&p4, 78, 50, NULL);
    person_print(&p4);

    printf("==================\n");

    p_cur = &p1;

    while (p_cur != NULL) {
        person_print(p_cur);
        p_cur = p_cur->next_person;
    }

    return 0;
}
</code>```

In particular I'm unsure about the signature of the functions in general and about the use of a Person * pointer.

When is it OK to not-pass a pointer but the struct/char array directly?

In most APIs I have seen so far, a pointer to the struct/char array is passed, like snprintf(char * s, ... ). But sometimes, like in getline(char **lineptr, ...) even a char ** is passed. Why? When make the distinction?

答:
Your question is a matter of opinion, however, it looks like Person is generally supposed to be allocated in the heap (read about C dynamic memory allocation).

Then you should define and document how Person-s are allocated and who is in charge of free-ing them and when.

I would suggest to have a function to create Person-s like

```<code>Person* make_person(unsigned p_age, p_weight) {
   Person* p = malloc(sizeof(Person));
   if (!p) { perror("malloc"); exit(EXIT_FAILURE); };
   p->age = p_age;
   p->weight = p_weight;
   p->next_person = NULL;
}
</code>```

We don't know what is next_person for. We might guess you want to have a global linked list of Person-s. Then you want some global pointer to the head of that list, the make_person should modify that global pointer, etc.

I would recommend against having Person automatic variables on the call stack (in particular, because that would limit the number of Person-s your program can handle, often to some staticly known small number; you may want to be able to handle millions of Person-s) Intuitively the call stack should not grow a lot (on current desktops with ordinary OSes like Linux or Windows, a stack limit of a few megabytes is typical) But we don't know what are you really coding.

Be afraid of undefined behavior, memory leaks. Read something about garbage collection. In a few months, you might be interested by Boehm's conservative garbage collector. If your system has it, consider using valgrind -for debugging purposes.

You might want a void destroy_person(Person*p) function which would either recursively (or iteratively) call destroy_person on the p->next_person or remove it from your global list, then call free(p) ...

Body:
Your question is a matter of opinion, however, it looks like Person is generally supposed to be allocated in the heap (read about C dynamic memory allocation).

Then you should define and document how Person-s are allocated and who is in charge of free-ing them and when.

I would suggest to have a function to create Person-s like

Person* make_person(unsigned p_age, p_weight) {
   Person* p = malloc(sizeof(Person));
   if (!p) { perror("malloc"); exit(EXIT_FAILURE); };
   p->age = p_age;
   p->weight = p_weight;
   p->next_person = NULL;
}

We don't know what is next_person for. We might guess you want to have a global linked list of Person-s. Then you want some global pointer to the head of that list, the make_person should modify that global pointer, etc.

I would recommend against having Person automatic variables on the call stack (in particular, because that would limit the number of Person-s your program can handle, often to some staticly known small number; you may want to be able to handle millions of Person-s) Intuitively the call stack should not grow a lot (on current desktops with ordinary OSes like Linux or Windows, a stack limit of a few megabytes is typical) But we don't know what are you really coding.

Be afraid of undefined behavior, memory leaks. Read something about garbage collection. In a few months, you might be interested by Boehm's conservative garbage collector. If your system has it, consider using valgrind -for debugging purposes.

You might want a void destroy_person(Person*p) function which would either recursively (or iteratively) call destroy_person on the p->next_person or remove it from your global list, then call free(p) ...


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
My experience with Adobe Reader and Nook for PC is that they are essential for travel and for going back and forth to work or class, but eReaders are not a panacea. You'll still need the hard cover as well, depending on the particular book. As you've noted, each format has its strengths and weaknesses, and using one does not preclude the other.

Nook for PC does a terrible job of presenting screen captures (for example the screencaps in the Nook version of Morville & Rosenfeld's "Information Architecture for the World Wide Web" are awful compared to the hard copy).

It's realistic to assume that many people will want both an electronic and hard copy for different situations, which is probably why some sellers now offer both as a package deal (for example, I got Luke Wroblewski's "Web Form Design" PDF for free when I bought the paperback).

Title: eBook editions of programming books


答:
Different linked libraries may use different heaps. This makes dynamic allocation and memory management tricky.

The most common way is to make Person an opaque struct (declared but not defined in the public header) and the programmer using it must use the functions in the library to get access to the attributes.

This means that allocating and freeing will be done inside the library using functions like Person* create_person(...) and void destroy_person(Person*).

Title: Idiomatic C API with regards to pointers

Body:
I am trying to get a better understanding of how one would structure an API in C.

I create a struct Person

I have a init function that sets data on that struct

I have multiple "helper" functions that work on that struct

I'm wondering if the following code in C can be considered idiomatic from the point of view of more seasoned C developers.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct Person Person;

struct Person
{
    unsigned int age;
    unsigned int weight;
    Person *next_person;
};

void person_init(Person *p, unsigned int age, unsigned int weight, Person *next_person)
{
    p->age = age;
    p->weight = weight;
    p->next_person = next_person;
}

void person_print(Person *p)
{
    printf("person is %dy old\n", p->age);
    printf("person weight is %dkg\n", p->weight);
}

int main(void)
{
    Person p1, p2, p3, p4;
    Person *p_cur;

    person_init(&p1, 28, 80, &p2);
    person_print(&p1);

    person_init(&p2, 58, 93, &p3);
    person_print(&p2);

    person_init(&p3, 60, 60, &p4);
    person_print(&p3);

    person_init(&p4, 78, 50, NULL);
    person_print(&p4);

    printf("==================\n");

    p_cur = &p1;

    while (p_cur != NULL) {
        person_print(p_cur);
        p_cur = p_cur->next_person;
    }

    return 0;
}
</code>```

In particular I'm unsure about the signature of the functions in general and about the use of a Person * pointer.

When is it OK to not-pass a pointer but the struct/char array directly?

In most APIs I have seen so far, a pointer to the struct/char array is passed, like snprintf(char * s, ... ). But sometimes, like in getline(char **lineptr, ...) even a char ** is passed. Why? When make the distinction?


问:
Modular Web App Network Architecture
Assuming that I am dealing with dedicated physical servers or VPSs, is it conceivable and does it make sense to have distinct servers setup with the following roles to host a web application?

Reverse Proxy

Web server

Application server

Database server

Specific points of interest:

I am confused how to even separate the web and application servers.  My understanding was that such 3-tier architectures were feasible.

It is unclear to me if the app server would reside directly between the web and database server, or if the web server could directly interact with the database as well.  The app server could either do the computational heavy-lifting on behalf of the app server or it could do heavy-lifting plus control all of the business logic (as implied in the diagram above, thus denying the web server of direct database access).

I am also unsure what role the reverse proxy (ex. nginx) could and should fulfill as a web server, given the above mentioned setup.  I know that nginx has web server features.  But I do not know if it makes sense to have the reverse proxy be its own VPS, given that the web server–in theory–would be separate from the app server.

答:
For a 3-tier architecture you are (partly) trying to scale. This means that you will offload some of the processing from the single database to a few application servers, and offload processing from them to many web servers. This also allows you to write code for each tier that is specialised, so the DB server will only run the DB, the app servers will only read (and cache) data and apply business logic, and the web servers will only handle presentation of the results to the clients.

There are other reasons to make a 3-tier architecture like this, security is one big reason - in such secure architectures the web server is considered the most likely to be compromised and therefore runs in a low-privilege environment (eg no direct access to the DB - if or when someone gains access to your webserver and it can read any DB table, then all your passwords are theirs. If all it can do is make an API call to the application server they also have to hack the app server too).

You can create such an architecture without many physical servers, either run them on VMs or just create each tier as a separate service - eg. the webserver is one, and its code calls a service that would be located on the app server if you had one but otherwise is just a local service that you communicate with using the same comms channel.

In many ways its easy to conceptualise this architecture - if you use any 3rd party service then you are already n-tier, the "application server" is whichever 3rd party service you consume. So if you use a Google mapping service for part of your site, its obviously running on a different server and you are making network calls to get the data which you combine with your own to build a page. Replace the Google service with your own that talks to your own DB nd you have a 3-tier service!

Reverse proxies are generally a security thing, in that it protects the web server from attackers - they have to bypass the proxy which should be difficult as it has a very small attack surface. A 3-tier architecture often has the webserver perform this role as it doesn't do much apart from generate HTML from data supplied to it by the application services.

Title: Modular Web App Network Architecture


问:
Client wants source code, but it contains a lot of shared code I reuse with other projects
I have a client who would like me to deliver the source code with a developed application binary. They originally said nothing about source code, but they recently said they need it. The contract is not finalized. They agreed to the work, did not sign, and then came back with this clause.

The issue is: I have a code base I've created over the years and used as a template for most of the applications I write. It is far larger than the scope of the project.

I also intend to use it for a product, so I really don't wish to provide it for a relatively small project.

I'm guessing this is not the first time that this has happened in this industry. What is the best way to circumvent this issue? I'm guessing things like shared libraries could help.

答:
This may be too late for you, in that you may already have agreed contractually to do this, and you could have agreed to mutually incompatible terms with different customers.

There are two ways in which you can provide your customers with your source code. Ownership of the copyright and licensed.

Some customers will want ownership of the source code.  This means, at the end of the process they will pay you money and you will in exchange give them copyright copyright of the code you create for them. One reason for this is if they see significant potential for intellectual property in the source code, and may want to value this on their company balance sheet. In this scenario, you will have no entitlement to continued use of that source code for other projects, unless you also obtain a license from your customer giving you this entitlement.

If your customer is buying an 'off the shelf' product from yourselves, they would expect to be receiving a license to use the software, not ownership of the source code.  They should be expecting that you are selling the same (or similar) software to many other organisations, and that they are hopefully benefiting from a lower cost of purchase due to the wider customer base.

However, the situation in this question is a mishmash of the two.

Here is what I would want to be able to do.  I would grant your customer a license to use (and modify) your shared code.  If quizzed by the customer, I would point out that this is shared code that you have already used in multiple projects and have current bids in place for future work that are based on you continuing to use this work.  point out that this has resulted in less time on this project for your customer and that they have paid a lower price as a result. Like other shared libraries of code used by the project, they have a license in place to use this code, and to allow other development teams to develop this, and other projects based on this library.  However, if they would rather ownership of all the code, you are willing to create a replacement, but this would be an additional charge.

Depending on what you have already committed yourself to, you could be having to write a replacement functionality for free, or giving away your source code.

Remember, there are different types of libraries.  The Standard Template Library in C++ is a good example of a library that is included at a source code level and is compiled into a project executable that may be quite similar to how you have used your common code.


问:
Pick dynamically the right Factory Class with Inversion of Control
I have a TreeView and I want to enable the context menu when clicking with the right mouse button. It is composed by items from different classes, but they all share the same base class.

So, I was considering to create a FactoryClass for each different item class that simply returns a custom IContextMenu interface (that later will be used by some other part of program to actually render the menu).

This is the current workflow I have in mind

The TreeView intercept the right click and request to another class
(let's call it ContextMenuFactory) to create a Context menu for
that item type

ContextMenuFactory redirect to a specific
factory class associated to the input item type (like IFooItemContextMenuFactory)

IFooItemContextMenuFactory class actually create the IContextMenu instance

What makes difficult this task is the second step.

I don't know how can I organize my code in order to make it dynamic because the only solution I have in mind it's just to implement a switch and create the factory class after I have recognized the type.

The ideal way would be to use the container to find the configured implementation, in this way I don't have to modify every time I create a new item type the switch previously suggested.

答:
I would do this:

For every class that implements IContextMenu create a Factory/Creator. For example for a class named TypeAContextMenu create a TypeAContextMenuCreator, for TypeBContextMenu create a TypeBContextMenuCreator, etc. Every creator implements the same interface, like say IContextMenuCreator, they just have a create() method that returns an object of type IContextMenu;

Create a HashMap, instantiate all creators and put them in the HashMap with a tag:

```<code>Map<String,IContextMenuCreator> c = new HashMap<String,IContextMenuCreator>();
creator.put("TYPEA", new TypeAContextMenuCreator());
creator.put("TYPEB", new TypeBContextMenuCreator());
creator.put("TYPEC", new TypeCContextMenuCreator());
</code>```

Then the object you right-click on in the tree view should include the tag of its corresponding IContextMenuCreator as a member.

When you right-click, get the appropriate creator from the HashMap. No need for switches. When new types of contextual menus are created you only have to add them in one place.

IContextMenu cm = creators.get(tag).create();

Body:
I would do this:

For every class that implements IContextMenu create a Factory/Creator. For example for a class named TypeAContextMenu create a TypeAContextMenuCreator, for TypeBContextMenu create a TypeBContextMenuCreator, etc. Every creator implements the same interface, like say IContextMenuCreator, they just have a create() method that returns an object of type IContextMenu;

Create a HashMap, instantiate all creators and put them in the HashMap with a tag:

Map<String,IContextMenuCreator> c = new HashMap<String,IContextMenuCreator>();
creator.put("TYPEA", new TypeAContextMenuCreator());
creator.put("TYPEB", new TypeBContextMenuCreator());
creator.put("TYPEC", new TypeCContextMenuCreator());

Then the object you right-click on in the tree view should include the tag of its corresponding IContextMenuCreator as a member.

When you right-click, get the appropriate creator from the HashMap. No need for switches. When new types of contextual menus are created you only have to add them in one place.

IContextMenu cm = creators.get(tag).create();


问:
Should HTTP Request/Response objects be immutable?
I think it's safe to say that most web applications are based on the request/response paradigm.  PHP has never had a formal abstraction of these objects.  One group is trying to change this: https://github.com/php-fig/fig-standards/blob/master/proposed/http-message.md

However, they sort of got side tracked on the issue of immutability. On the one hand, request/response object generally need very little change during their life cycle.  On the other hand, the response object in particular often needs HTTP headers to be added.

Furthermore, immutability has never really caught on in the land of PHP.

What advantages do people see in using immutable request/response objects?

Let's suppose you are returning a json object.

```<code>$response = new JsonResponse($item);
</code>```

Nice and simple.  But it turns out that the request was a Cross-Origin Resource Sharing(CORS) request.  The code that generates the response should not care but somewhere downstream is a process that will add the necessary Access-Control headers.  Any advantage to keeping the original response and creating a new one with the additional headers?  Or is it strictly a question of programming style.

The request object is a bit more interesting.  It starts off the same:

```<code>$request = new Request('incoming request information including uri and headers');
</code>```

The initial information should not need to be changed.  However, as the request get's passed along there is often a need to add additional processing information.  For example, you may have a url matcher which decides what action should be executed for a given request.

```<code>$request->setAttribute('action',function() {});
</code>```

Actually executing the action is the responsibility of a down stream process.  You could have a mutable RequestAttributesCollection which wraps the immutable request but that tends to be a bit awkward in practice.  You could also have a request that's immutable except for an attributes collection.  Exceptions tends to be awkward as well.  Any experience on dealing with these sorts of requirements?

答:
What advantages do people see in using immutable request/response objects?

I agree with @MainMa's statement "I'm not sure if the slight benefit of readability compensates the possible lack of flexibility" and personally I don't see any practical and useful aspects of forcing PHP HTTP Request temporary objects or PHP HTTP Response temporary objects to be immutable

Any experience on dealing with these sorts of requirements?

Microsoft's Windows Presentation Foundation framework introduces concept of freezable objects. Once frozen, such objects become

immutable (throw exceptions when modification is attempted),

faster to use (property getters don't need to do any fancy "what's my value?" decisions any more),

consuming less memory (internal helper data structures and caches etc. can be reduced to their most time & space efficient representation)

and shareable

Although it is used as GUI speed optimization, the concept itself is applicable also elsewhere, including it's benefits

Nancy ("Lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono") describes benefit of immutability in one of commit comments as

...we can assume our caches are immutable if they're off, which means we have no locks so faster performance (although the hit isn't massive)...

I did not find any other noteworthy comments about immutability, but the benefit of reusable, cacheable response objects may apply to PHP as well

The above may look like off-topic answers, but I'm not aware of anything else and that's why I think the immutability requirement is an artificial problem and rather matter of preference or coding style etc.


问:
How can C++ make it possible to use dynamic container classes even in embedded systems?
How can C++ make it possible to use dynamic container classes even in embedded systems?

Background info:

I've been working with PIC (C) and AVR (C++) processors and at the moment (PIC C) I'm trying to send a text (with undefined length) to a method that only sends this string with a HTTP POST (so it has to know the length beforehand).

Problem & question:

On C++ this could easily be achieved with a container class/dynamic array.
Though, when using C, I (guess) I'm continiously overwriting memory addresses (When I use a pointer and then change the length)?

How does C++ (efficiëntly?) manage dynamic arrays? Are all bits off the dynamic array scattered throughout your memory and how does it find these back? Or does it secretly allocate memory/blocks of memory?

答:
C++ can do it the same way C does. All C++ gives you is easier-to-use containers that wrap much of the low-level detail.

For example, a string class can (and does) hold a block of memory on the stack for short strings, only allocating a heap buffer for larger ones. This buffer is exactly like a C string buffer, if the string resizes, the string class will resize it in the same way a C programmer would by allocating a new buffer and copying the old data into it, except that possibly the string class will over-allocate the buffer size to allow for future appending to the string. Some string classes will count the length of the string using strlen, others will store the length as a member variable that it keeps up to date.

Arrays are managed in the same way, but there are specialised containers that give you things like linked lists.


问:
What are the advantages of linear probing over separate chaining or vice-versa when implementing hash tables?
I've been brushing up on algorithms and reviewed these two methods of implementing hash tables.  It seems like they largely have similar performance characteristics and memory requirements.

I can think of some disadvantages to linear probing -- namely, that widening the array could be expensive (but this is done, what, 2 log N times at most?  Probably not a big deal) and that managing deletions is a bit more difficult.  But I'm assuming there are advantages, too, or it wouldn't be presented in textbooks as a viable method of implementation next to the more obvious implementation.

Why would you choose one over the other?

答:
With linear probing (or any probing really) a deletion has to be "soft". This means you need to put in a dummy value (often called a tombstone) that won't match anything the user could search for. Or you would need to rehash every time. Rehashing when too many tombstones build up is still advised or some strategy to defrag the graveyard.

Separate chaining (each bucket is a pointer to a linked list of values) has the disadvantage that you end up searching a linked list with all cache-related issues at hand.

One other advantage of the probing method is that the values all live in the same array. This makes copy-on-write very easy by just copying only the array. If you can be assured the original is not modified by way of class invariant then a taking a snapshot is O(1) and can be done without locking.

ContentLicense: CC BY-SA 4.0


问:
Has pre-increment operators become that common?
Bit of background to explain the reasoning: I've been programming for a good while, but took a break between 2012 and 2014 for other stuff. Before that break, I would hardly ever hear about "++i", let alone hear decent explanations about it ("...isn't it... just better?" was common to hear). Now, however, I see it everywhere, and even some text editors seem to use this by default (Sublime Text comes to mind).

So I've been wondering; did "++i" become suddenly very popular as of late, or is my new work environment pro-prefix increment operators?

(another possible solution is that my old environment wasn't big on "++i" for some reason)

Note that I am definitely not asking whether this is a good thing or not; I'm well aware of how pre-increment operators work, and honestly there are enough debates about this on SO. I'm just asking if this is a local trend, or a more global one. Also this is strictly for C, not C# or Java.

答:
In C++, the pre-increment operator may be written to return a reference to the incremented object. The post-increment operator has to return a copy (because the return value is the value before the increment operation).

So, if you're using increment and don't care about the return value (such as in a loop increment), then you want to prefer pre-increment as you might be incrementing something that's costly to copy.

In C this is irrelevant, but I know that once I developed the habit in C++, it spread to my C code as well.


问:
Is the H2 addendum to the EPL and MPL compatible with these licenses?
The H2 Database License is dual licensed under the MPL 2.0 and under the EPL 1.0 with this addendum:

However, nobody is allowed to rename H2, modify it a little, and sell
  it as a database engine without telling the customers it is in fact
  H2. This happened to HSQLDB: a company called 'bungisoft' copied
  HSQLDB, renamed it to 'RedBase', and tried to sell it, hiding the fact
  that it was in fact just HSQLDB. It seems 'bungisoft' does not exist
  any more, but you can use the Wayback Machine and visit old web pages
  of http://www.bungisoft.com.

I have no desire to rebrand the H2 database, but I am curious if this addendum is compatible with either  the MPL 2.0 the EPL 1.0. My reading of the MPL and the EPL is that this addendum is not compatible with either license.

The MPL says this:

Each Contributor hereby grants You a world-wide, royalty-free,
  non-exclusive license: under intellectual property rights (other than
  patent or trademark) Licensable by such Contributor to use, reproduce,
  make available, modify, display, perform, distribute, and otherwise
  exploit its Contributions, either on an unmodified basis, with
  Modifications, or as part of a Larger Work; and

The EPL says this:

a) Subject to the terms of this Agreement, each Contributor hereby
  grants Recipient a non-exclusive, worldwide, royalty-free copyright
  license to reproduce, prepare derivative works of, publicly display,
  publicly perform, distribute and sublicense the Contribution of such
  Contributor, if any, and such derivative works, in source code and
  object code form.

The addendum seems to conflict with both of these excerpts. If the addendum does conflict does it still make sense legally?

Also this part of the addendum seems legally ambiguous "nobody is allowed to rename H2, modify it a little, and sell it". Do you guys think it is legally valid?

To add more detail to this, the MPL 2 FAQ states that the only restrictions the MPL places on modifying and distributing MPL licensed code are:

You must inform the recipients that the source code is made available to them under the terms of the MPL (Section 3.1), including any Modifications (as defined in Section 1.10) that you have created.

You must make the grants described in Section 2 of the license.

You must respect the restrictions on removing or altering notices in the source code (Section 3.4).

It seems clear that the MPL 2 allows another person to make any changes they want to MPL licensed code (including changing the name of the product) and distribute it as long as they make the code available and don't change the license or copyright on the original code.

答:
A software license tells you two things:

What you can do with the software

What you cannot do with the software

However, a software license does not offer any guarantees. Specifically:

It doesn't prevent anyone from suing you, even if you follow the license in good faith, and

It doesn't prevent said person from winning in court, if they do sue you.

The only important consideration is this: is the license legally enforceable?  As I am not a lawyer, I can't answer that question with any certainty.  However, it seems clear to me that H2 does have the right to specify conditions: specifically that you cannot make some non-trivial modification to their code and pass it off as your own product with a different name.  This is both reasonable and fair.

Whether the resulting license can still be called MPL or EPL is an open question.  However, note that both the MPL and EPL already contain provisions that could be interpreted to mean what H2 states in starker language :

The MPL uses the language "Larger Work."  A Larger Work means a work that combines software covered by the MPL with other material.  It is generally understood that such a Larger Work is an application that uses the MPL-covered work to perform functions that facilitate the operation of the Larger Work as a whole, not a trivial wrapper or some minor modification that merely results in the same program with a different name.

The EPL uses the language "Derived Work."  A Derived work is a work incorporating the original covered software, but it is a new work.  Derived works are generally understood to be "transformative;" that is, the new program contains substantially more functionality than the covered software.

So what's the bottom line?  A case could be made that, by modifying the MPL and EPL licenses with H2's "No lamers" manifesto, they are changing the licenses in such a way that you can no longer call them MPL or EPL.  But, at the end of the day, they don't want you to make some trivial change to the code, change the license and call it your own.  So you shouldn't.

tl;dr: Don't be a lamer.


问:
Git branch usage - keep an old, never merged branch around or delete it?
I'm working on a small project, and I am using Github as version control. I made a new branch to test something out, and have decided I liked the previous method better (in the master branch).

What is the intended paradigm for branches in git?  Do they denote that a different attempt was made, and it was not used (if the branch was not merged), or would it imply that more work is being done in that direction?

My more practical question is: Should I just delete the branch, or can I just leave it there (as I'd like to leave the "test" code there, in case I need it later)?

答:
The new Branch wont interfere on the master branch
You should leave it there and keep writing and commit on the master branch</p>


问:
Is it advisable to disable the Microsoft enforced coding standards in VC# 2010?
Coming from eclipse I've developed my own coding standards which I got used to. In Visual C# 2010 however, it appears that some coding standards that MS recommends are enforced in the default configuration.

E.g.: I'm used to write conditional statements like this:

```<code>if (somecondition) {
    return true;
} else {
    return false;
}
</code>```

But the braces are forced to a newline in visual c#. Is it recommended to use that standard ?

答:
The old coding standards seem like they are from Java environment. I think it's better to stick to coding standards that the new language uses than transfers standards from language to language.

You will save yourself a trouble when working with someone else or taking/using existing code.

OwnerDisplayName: Max


问:
How much work should I place inside a lock statement?
I am a junior developer working on writing an update for software that receives data from a third-party solution, stores it in a database, and then conditions the data for use by another third-party solution. Our software runs as a Windows service.

Looking at the code from a previous version, I see this:

```<code>        static Object _workerLocker = new object();
        static int _runningWorkers = 0;
        int MaxSimultaneousThreads = 5;

        foreach(int SomeObject in ListOfObjects)
        {
            lock (_workerLocker)
            {
                while (_runningWorkers >= MaxSimultaneousThreads)
                {
                    Monitor.Wait(_workerLocker);
                }
            }

            // check to see if the service has been stopped. If yes, then exit
            if (this.IsRunning() == false)
            {
                break;
            }

            lock (_workerLocker)
            {
                _runningWorkers++;
            }

            ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);

        }
</code>```

The logic seems clear: Wait for room in the thread pool, make sure the service hasn't been stopped, then increment the thread counter and queue the work. _runningWorkers is decremented inside SomeMethod() inside a lock statement that then calls Monitor.Pulse(_workerLocker).

My question is:
Is there any benefit in grouping all the code inside a single lock, like this:

```<code>        static Object _workerLocker = new object();
        static int _runningWorkers = 0;
        int MaxSimultaneousThreads = 5;

        foreach (int SomeObject in ListOfObjects)
        {
            // Is doing all the work inside a single lock better?
            lock (_workerLocker)
            {
                // wait for room in ThreadPool
                while (_runningWorkers >= MaxSimultaneousThreads)
                {
                    Monitor.Wait(_workerLocker);
                }
                // check to see if the service has been stopped.
                if (this.IsRunning())
                {
                    ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);
                    _runningWorkers++;
                }
                else
                {
                    break;
                }
            }
        }
</code>```

It seems like, it may cause a little bit more waiting for other threads, but then it seems like locking repeatedly in a single logical block would also be somewhat time-consuming. However, I'm new to multi-threading, so I'm assuming that there are other concerns here that I'm unaware of.

The only other places where _workerLocker gets locked is in SomeMethod(), and only for the purpose of decrementing _runningWorkers, and then outside the foreach to wait for the number of _runningWorkers to go to zero before logging and returning.

Thanks for any help.

EDIT 4/8/15

Thanks to @delnan for the recommendation to use a semaphore. The code becomes:

```<code>        static int MaxSimultaneousThreads = 5;
        static Semaphore WorkerSem = new Semaphore(MaxSimultaneousThreads, MaxSimultaneousThreads);

        foreach (int SomeObject in ListOfObjects)
        {
            // wait for an available thread
            WorkerSem.WaitOne();

            // check if the service has stopped
            if (this.IsRunning())
            {
                ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);
            }
            else
            {
                break;
            }
        }
</code>```

WorkerSem.Release() is called inside SomeMethod().

答:
IMHO you are asking the wrong question - you should not care so much about efficiency trade-offs, but more about correctness.

The first variant makes sure _runningWorkers is only accessed during a lock, but it misses the case where _runningWorkers might be changed by another thread in the gap between the first lock and the second. Honestly, the code looks to me if someone has put blindly locks around all access points of _runningWorkers without thinking about the implications and the potential errors. Maybe the author had some superstitious fears about executing the break statement inside the lockblock, but who knows?

So you should actually use the second variant, not because its more or less efficient, but because its (hopefully) more correct than the first one.


答:
This is not a question of performance. It is first and foremost a question of correctness. If you have two lock statements, you can not guarantee atomicity for operations that are spread between them, or partially outside the lock statement. Tailored for the old version of your code, this means:

Between the end of the while (_runningWorkers >= MaxSimultaneousThreads) and the _runningWorkers++, anything at all may happen, because the code surrenders and re-acquires the lock in between. For example, thread A might acquire the lock for the first time, wait until there some other thread exits, and then break out of the loop and the lock. It is then preempted, and thread B enters the picture, also waiting for room in the thread pool. Because said other thread quit, there is room so it doesn't wait very long at all. Both thread A and thread B now go on in some order, each incrementing _runningWorkers and starting their work.

Now, there are no data races as far as I can see, but logically it's wrong, since there are now more than MaxSimultaneousThreads workers running. The check is (occasionally) ineffective because the task of taking a slot in the thread pool is not atomic. This should concern you more than small optimizations around lock granularity! (Note that conversely, locking too early or for too long can easily lead to deadlocks.)

The second snippet fixes this problem, as far as I can see.
A less invasive change to fix the problem might be putting the ++_runningWorkers right after the while look, inside the first lock statement.

Now, correctness aside, what about performance? This is hard to tell. Generally locking for a longer time ("coarsely") inhibits concurrency, but as you say, this needs to be balanced against the overhead from the additional synchronization of fine-grained locking. Generally the only solution is benchmarking and being aware that there are more options than "lock everything everywhere" and "lock only the bare minimum". There is a wealth of patterns and concurrency primitives and thread-safe data structures available. For example, this seems like the very application semaphores were invented for, so consider using one of those instead of this hand-rolled hand-locked counter.

Title: How much work should I place inside a lock statement?

Body:
I am a junior developer working on writing an update for software that receives data from a third-party solution, stores it in a database, and then conditions the data for use by another third-party solution. Our software runs as a Windows service.

Looking at the code from a previous version, I see this:

```<code>        static Object _workerLocker = new object();
        static int _runningWorkers = 0;
        int MaxSimultaneousThreads = 5;

        foreach(int SomeObject in ListOfObjects)
        {
            lock (_workerLocker)
            {
                while (_runningWorkers >= MaxSimultaneousThreads)
                {
                    Monitor.Wait(_workerLocker);
                }
            }

            // check to see if the service has been stopped. If yes, then exit
            if (this.IsRunning() == false)
            {
                break;
            }

            lock (_workerLocker)
            {
                _runningWorkers++;
            }

            ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);

        }
</code>```

The logic seems clear: Wait for room in the thread pool, make sure the service hasn't been stopped, then increment the thread counter and queue the work. _runningWorkers is decremented inside SomeMethod() inside a lock statement that then calls Monitor.Pulse(_workerLocker).

My question is:
Is there any benefit in grouping all the code inside a single lock, like this:

```<code>        static Object _workerLocker = new object();
        static int _runningWorkers = 0;
        int MaxSimultaneousThreads = 5;

        foreach (int SomeObject in ListOfObjects)
        {
            // Is doing all the work inside a single lock better?
            lock (_workerLocker)
            {
                // wait for room in ThreadPool
                while (_runningWorkers >= MaxSimultaneousThreads)
                {
                    Monitor.Wait(_workerLocker);
                }
                // check to see if the service has been stopped.
                if (this.IsRunning())
                {
                    ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);
                    _runningWorkers++;
                }
                else
                {
                    break;
                }
            }
        }
</code>```

It seems like, it may cause a little bit more waiting for other threads, but then it seems like locking repeatedly in a single logical block would also be somewhat time-consuming. However, I'm new to multi-threading, so I'm assuming that there are other concerns here that I'm unaware of.

The only other places where _workerLocker gets locked is in SomeMethod(), and only for the purpose of decrementing _runningWorkers, and then outside the foreach to wait for the number of _runningWorkers to go to zero before logging and returning.

Thanks for any help.

EDIT 4/8/15

Thanks to @delnan for the recommendation to use a semaphore. The code becomes:

```<code>        static int MaxSimultaneousThreads = 5;
        static Semaphore WorkerSem = new Semaphore(MaxSimultaneousThreads, MaxSimultaneousThreads);

        foreach (int SomeObject in ListOfObjects)
        {
            // wait for an available thread
            WorkerSem.WaitOne();

            // check if the service has stopped
            if (this.IsRunning())
            {
                ThreadPool.QueueUserWorkItem(SomeMethod, SomeObject);
            }
            else
            {
                break;
            }
        }
</code>```

WorkerSem.Release() is called inside SomeMethod().


问:
Why are the test values the same for FIFO and LRU?
I had a computer science assignment where we compared FIFO, LRU and random policy for a cache memory. FIFO and LRU were equally good as improvements to a random policy. Why? Is it just a coincidence? We use a MIPS emulator software to do the assignment. </p>

答:
It is not exactly a coincidence, it is a failure of your testing methodology to use the cache in such a way that would make the superiority of LRU over FIFO evident.

The superiority of LRU is evident if your memory accesses consist partly of random accesses, resulting mostly in cache misses, and partly of accesses from a small locality which is smaller than your cache.  These localized accesses will mostly result in cache hits for LRU, but will often result in misses with FIFO, because FIFO will offload them just because they were loaded a long time ago, regardless of the fact that they were used very recently.

If you post your methodology we might be able to tell precisely what's wrong with it.


问:
C# Constructor and private LINQ to SQL members
I am extending an application I have developed so that it is more broadly useful for multiple jobs, rather than the single job I created it for.  There are a number of tables that I get from SQL Server with LINQ to SQL.  Instead of having all records from the database populate the application, I want to filter first by job.  Currently my viewmodels all have the same construction: a set of private ObservableCollections that get the data through the LINQ to SQL classes, a constructor that sets up binding commands (trying to practice good MVVM), and then the logic.  So what I do now is something like this:

```<code>partial class MainViewModel : InotifyPropertyChanged
{
    ObservableJobs _oJob = new ObservableJobs(_dataDc);
    public MainViewModel()
    {
        NumRecords.Value = oJob.View.Count;
    }

    public ViewableCollection<Job> oJob
    {
        get { return _oJob; }
    }
    // and then the stuff that the viewmodel takes care of follows
}

public class ViewableCollection<T> : ObservableCollection<T>
{
    private ListCollectionView _View;
    public ListCollectionView View
    {
        get
        {
            if (_View == null)
            {
                _View = new ListCollectionView(this);
            }
            return _View;
        }
    }
}
</code>```

It strikes me that _oJob is populated before the constructor is run, as the NumRecords.Value is assigned the actual records from the database.  Is it better practice to declare outside the constructor and assign inside the constructor, or is it only a matter of timing/ sequencing when things happen? In my next phase I think I need to control the timing of when things get loaded better, so that I minimize the number of records transferred from the SQL Server.

If I try to declare it this way I get an exception, inner exception says "Value cannot be null. Parameter name source".

```<code>    ObservableJobs _oJob;// = new ObservableJobs(_dataDc);
    public MainViewModel()
    {
        _oJob = new ObservableJobs(_dataDc);
        NumRecords.Value = oJob.View.Count;
    }
</code>```

How do I go about controlling how I instantiate the observable collections so that I can set a jobID (or pass one to the constructor along with the datacontext) and filter the querys?

Here is the ObservableJobs class:

```<code>class ObservableJobs: ViewableCollection<Job>
{
    public ObservableJobs(DocControlDC dataDc)
    {
        foreach (Job j in dataDc.Jobs)
        {
            this.Add(j);
        }
    }
}
</code>```

答:
Why not do DI instead of newing up the object right in that class? That way you don't have to bother about the original problem because it will be initialized for you and then be passed in.

Also it would make it much easier to test your view model.

But to answer your original question. In case you have to initialize inside of your class then I would say:

It is a matter of efficiency.

Here is the rule of thumb that I go by:

If the property being instantiated is going to be repeating in multiple constructors the same way then I just take it out and initialize it on the top. It is easier to see on the top when you are trying to understand the class as well (Or have a private constructor that rest of the overloads call as a part of initialization - this however creates unnecessary amount of duplicated code - having it on the top is just one liner).

If it is going to be initialized differently per constructor then I keep it inside of the constructor, which is self-explanatory.


答:
I resist the urge to fun of you for not simplifying that statement to return somecondition, since that's clearly not what you're asking about.

This is one of the classic style holy wars. Personally, I prefer the C# convention because visual alignment improves readability (for me), but in practice, I adopt the convention that's most common in the development community in question.

That is to say, in Java, I typically start the brace on the conditional line. In C#, I start a new line. In ruby or python there are no braces needed. In Lisp, I typically follow elisp conventions.

My opinion is simple: following a convention is more important than which convention you use.

Title: Is it advisable to disable the Microsoft enforced coding standards in VC# 2010?

Body:
Coming from eclipse I've developed my own coding standards which I got used to. In Visual C# 2010 however, it appears that some coding standards that MS recommends are enforced in the default configuration.

E.g.: I'm used to write conditional statements like this:

```<code>if (somecondition) {
    return true;
} else {
    return false;
}
</code>```

But the braces are forced to a newline in visual c#. Is it recommended to use that standard ?


问:
Why are my unit tests so expensive?
I am a Java developer, working on a small project. We are three people in the team, we have a budget for 3 months of coding (+ some time for the Analyst, Project Manager and QA team). It is a small project, the budget is really limited. There is some support in our organization to do the unit tests, but I didn't meet any expert in this area. Motivated by books and discussions, I started to do the unit tests. I have some limited experience with frameworks and approaches, so I don't test every getter, I focus on business code, I use Mockito and MoreUnit Eclipse plugin to generate the skeleton and Mocks. I design my code upfront, I use plenty of design patterns, I keep my code clean, with short methods, I respect the Single Responsibility Principe and I have much more public methods then the private ones. It is not perfect, but it is the best I can do after 5 years of commercial experience in one corporation and one mid size company.

So why does making unit tests take me the same or even higher amount of time then coding productive code? After last two days of unit testing I found just one minor bug and it didn't come from the tests, I just randomly found it when I was looking into the production code. Where are the benefits the people are talking about? Every refactoring caused just throwing away existing unit tests and they never told me if I influenced the rest of the system. Every class I test has mocked out its surroundings, so if I change one class, it will not affect the other tests and I won't know if I messed up the system by my change.

What am I missing? Am I doing it wrong?

Edit: To add some numbers, I spend about 80% of time by designing and coding, and 20% by unit testing, so just small amount of my code is covered by tests. I try to do unit test fot 1,5 month, usually after I finish some functionality and roughly test in on my local development machine.

答:
The key is to test the intention of your code.

This way even if you refactor the way your intention is being implemented you will still be able to have valid unit test because it is still the same intention.

As you have mentioned yourself, if you have limited resources, then do what is most important and that would be business logic.

Also don't forget about acceptance and integration tests since these could eliminate the need for you to be testing each and every layer individually.

If you are following all of those best practices, as you have mentioned above, then writing unit tests shouldn't be that difficult - maybe you are just new to the testing paradigm and with practice you will accelerate and be able to produce code more quickly with better quality.

Title: Why are my unit tests so expensive?


答:
Why are my unit tests so expensive?

For the same reason divorce is so expensive:

It is worth it.

In my experience (bizdev, C#/Java over more than a decade now), writing unit tests for code takes about half the time as writing the code itself - so 33% of your total coding time. Some things will be more. Some things will be less. When you're just learning to write unit tests, it will be slower than "normal" coding. That (in my experience) provides the sweet spot for most code between time spent and effective testing. That will usually be a good 70-80% code coverage, give or take. Some environments might demand more rigorous quality. Fewer might need less.

That might seem like a lot, but having the tests saves you time you would otherwise spend tracking down QA bugs, making patches, manually testing, or suffering from code you can't effectively refactor.

so if I change one class, it will not affect the other tests and I won't know if I messed up the system by my change.

Sure you will, if you mocked out the interactions between your classes properly. If you changed your class and your unit tests pass (all inputs are handled as expected, and provide legal/expected outputs) then you can't impact the rest of the system, since the interface between your class and the outside world is intact and well tested.

Title: Why are my unit tests so expensive?

Body:
I am a Java developer, working on a small project. We are three people in the team, we have a budget for 3 months of coding (+ some time for the Analyst, Project Manager and QA team). It is a small project, the budget is really limited. There is some support in our organization to do the unit tests, but I didn't meet any expert in this area. Motivated by books and discussions, I started to do the unit tests. I have some limited experience with frameworks and approaches, so I don't test every getter, I focus on business code, I use Mockito and MoreUnit Eclipse plugin to generate the skeleton and Mocks. I design my code upfront, I use plenty of design patterns, I keep my code clean, with short methods, I respect the Single Responsibility Principe and I have much more public methods then the private ones. It is not perfect, but it is the best I can do after 5 years of commercial experience in one corporation and one mid size company.

So why does making unit tests take me the same or even higher amount of time then coding productive code? After last two days of unit testing I found just one minor bug and it didn't come from the tests, I just randomly found it when I was looking into the production code. Where are the benefits the people are talking about? Every refactoring caused just throwing away existing unit tests and they never told me if I influenced the rest of the system. Every class I test has mocked out its surroundings, so if I change one class, it will not affect the other tests and I won't know if I messed up the system by my change.

What am I missing? Am I doing it wrong?

Edit: To add some numbers, I spend about 80% of time by designing and coding, and 20% by unit testing, so just small amount of my code is covered by tests. I try to do unit test fot 1,5 month, usually after I finish some functionality and roughly test in on my local development machine.