问:
Efficient methods for storing tens of millions of objects for querying, with a high number of inserts per second?
This is basically a logging/counting application that is counting the number of packets and counting the type of packet, etc. on a p2p chat network. This equates to about 4-6 million packets in a 5 minute period. And because I only take a "snapshot" of this information, I am only removing packets older than 5 minutes every five minutes. So the maximum about of items that will be in this collection is 10 to 12 million.

Because I need to make 300 connections to different superpeers, it is a possibility that each packet is trying to be inserted at least 300 times (which is probably why holding this data in memory is the only reasonable option).

Currently, I have been using a Dictionary for storing this information. But because of the large amount of items I'm trying to store, I run into issues with the large object heap and the amount of memory usage continuously grows over time.

```<code>Dictionary<ulong, Packet>

public class Packet
{
    public ushort RequesterPort;
    public bool IsSearch;
    public string SearchText;
    public bool Flagged;
    public byte PacketType;
    public DateTime TimeStamp;
}
</code>```

I have tried using mysql, but it was not able to keep up with the amount of data that I need to insert (while checking to make sure it was not a duplicate), and that was while using transactions.

I tried mongodb, but the cpu usage for that was insane and did not keep either.

My main issue arises every 5 minutes, because I remove all packets that are older than 5 minutes, and take a "snapshot" of this data. As i'm using LINQ queries to count the number of packets containing a certain packet type. I also am calling a distinct() query on the data, where I strip 4 bytes (ip address) out of the keyvaluepair's key, and combine it with the requestingport value in the Value of the keyvalupair and use that to get a distinct number of peers from all the packets.

The application currently hovers around 1.1GB of memory usage, and when a snapshot is called it can go so far as to double the usage.

Now this wouldn't be an issue if I have an insane amount of ram, but the vm I have this running on is limited to 2GB of ram at the moment.

Is there any easy solution?

答:
(I know this is an old question, but I ran across it while looking for a solution to a similar problem where the second gen garbage collection pass was pausing the app for several seconds, so recording for other people in similar situation).

Use a struct rather than a class for your data (but remember it's treated as a value with pass-by-copy semantics). This takes out one level of searching the gc has to do each mark pass.

Use arrays (if you know the size of data you are storing) or List - which uses arrays internally. If you really need the fast random access, use a dictionary of array indices. This takes out another couple of levels (or a dozen or more if you are using a SortedDictionary) for the gc to have to search.

Depending on what you are doing, searching a list of structs may be faster than the dictionary lookup (due to the localisation of memory) - profile for your particular application.

The combination of struct&list reduces both the memory usage and the size of the garbage collector sweep significantly.

OwnerDisplayName: Josh


问:
Algorithm/research on detecting language of text
I am interested in finding an approach that will detect what language a string of text is. As Google translate does.</p>

答:
Actually, the easiest way is to use the google/ms translate api, they've done all the hard work for you.

Here's a webservice that you can use from Microsoft Translate:

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

ContentLicense: CC BY-SA 3.0


问:
Scrum: Writing the time it took to complete a task
In my organization when we move a task to the "Done" column we write the number of hours it took to complete the task. It can be useful when during retrospective the team tries to understand why certain stories took longer to implement than anticipated. However it is also burdensome and developers feel somewhat micromanaged or stressed when they have to do this.

What do you do in your teams? What do you recommend?

答:
As Sklivvz pointed, Scrum does'nt have the concept of left time over single task: im my experience, the tracking the time of single task can stress the developer in strong way (I remember my ex-boss saying me that he would to measure too the time of personal phone call and minutes in toilette :| ) and you consider context's events out your control (for example, corruption of rigid disks of repository machine and lose of the code (Yes, this heappens :)).

I think the the engaged time is an effect of definition of task; more the time is engaged, more the task has some big-effort-point or some unprevedible or unreproducible problematic event in the context, out your control. I go out the stime, why? Difficult in algorithmic? Late in receive the coherent requirements? Problems with configuration of hardware? Lost time in fixing old bug what give effects in new development?

In my experience, I thinks it's better to utilise some standard metric (Function Point, complexity, etc) and see if the task respect the normal values of this metric of the0re's too much difference.

It's the the business task what determines the effort time, not the time what determines the business goals of the software.


问:
What's the idea behind defining rectangles with two points?
It's not that this doesn't make sense, but it just works out awkward 99% of the time.

Often in 2D graphics rectangles are initialized, stored and manipulated as a pair of points.  In no particular language,

```<code>class Rect:
   p1, p2: point
</code>```

It makes more sense to define a rectangle as two x values and two y values, like this:

```<code>class Rect
   xleft, xright: int
   ytop, ybottom: int
</code>```

With two points, if at some place in the source code you want to make use of the y value of the top, you'd have to say rect.p1.y  (hmmm, stop and think, is it p1 or p2) but with the four values as plain data members, it's clear and direct:  rect.ytop (no thinking required!)     The use of two points means that in dealing with the vertical, you have to tangle the horizontal; there's an extraneous relation between indepenent elements.

How did this two-point idea come about and why does it persists?  Does it have some benefit over bare x and y coordinates?

ADDED NOTE: This question is in the context of X-Y aligned rectangles, such as in windows managers and GUI toolkits, not in the context of arbitrary shapes in drawing and painting app.

答: This is why I like Delphi's TRect.  It's defined as a variant record (union struct in C-speak) that can be interpreted either as a TopLeft and a BottomRight point, or Top, Left, Bottom and Right integers, whichever is more convenient at the moment.

ContentLicense: CC BY-SA 2.5


问:
Why is it hard to make a Java program 'appear native'?
Most Java applications don't look the same as C/C++ applications. Swing might have been designed on purpose to have a distincitve look, but based on what I've read, SWT for example tried to 'look native', and doesn't completley succeed.

My question is:

Why is it hard for the developers of the Java language to design a GUI system that copies exactly the look of native GUIs? What's different in native GUIs? Isn't it only a matter of designing buttons that look like 'native' buttons? Or does it go deeper than that?

答:
There is a trade-off between expecting your application to look as natural as possible on every system and expecting your application to work in the same way on each system. There is no "right" choice.

Moreover, even if you choose the "natural looking" side, you might want to protect the users of your graphic toolkit against "improvements" in the underlying native components and API which might break their application unexpectedly.

This is why some GUI toolkit developers prefer to provide their own components that mimic native ones, but provide their own implementation. On the other hand developing a functionally complete GUI toolkit is a significant effort and economic considerations may lead to cutting a few edges.

Note that this problem is not Java specific, but is faced by every company producing platform independent toolkits.


问:
Why is the Unix linker called "ld"
Tried to search the web and couldn't find an answer. It might have something to do with "load", but that doesn't make much sense to me.

Obviously, "ln" was already taken, but where does that "d" come from?

答:
Linkers in Linux were originally called loaders. See Assembly Language Step-by-Step: Programming with Linux by Jeff Duntemann:

Linking the Object code File

...Linux comes with its own linker, called ld. (The name is actually short for "load", and "loader" was what linkers were originally called, in the First Age of Unix, back in the 1970s.)

Title: Why is the Unix linker called "ld"


问:
What's the best way to explain branching (of source code) to a client?
The situation is that a client requested a number of changes about 9 months ago which they then put on hold with them half done.  They've now requested more changes without having made up their mind to proceed with the first set of changes.  The two sets of changes will require alterations to the same code modules.

I've been tasked with explaining why them not making a decision about the first set of changes (either finish them or bin them) may incur additional costs (essentially because the changes would need to be made to a branch then if they proceed with the first set of changes we'd have to merge them to the trunk - which will be messy - and retest them).

The question I have is this:

How best to explain branching of code to a non-technical client?

答: I wouldn't even try. Just tell them if they want to do both sets of changes now it will cost less than if you do a release now for their recent changes and then a later release that brings in the old-set of changes that are on hold. Why? Because a release itself costs money.</p>


问:
Selecting a point inside a non-convex polygon
There are a lot of algorithms which will tell you whether or not a given point is found inside a polygon.

I'm looking to write an algorithm which, given a non-convex polygon, will return a point which is inside the polygon.

I don't need the point to be in any specific location inside the polygon, but I prefer to receive a point which isn't very close to an edge, but that is not a deal-breaker. It's there merely to mark that polygon's planar straight-line graph (PSLG) as an internal shape for use with Shewchuck's Triangle library for some complicated constrained Delaunay triangulations.

My initial thinking is:

Compute the bounding box

Cast a ray from one corner in the direction of the opposite corner, or from the center of a bounding box edge to the opposite edge center.

Then, a point exactly between the first and second intersection will
be inside the polygon.

Is there a better approach?

答:
The following algorithm will do nicely:

```<code>p = randpoint();
while(!IsInsidePolygon(p, poly)) {
  p = randpoint();
}
</code>```

Big problem is choosing randpoint() so that the whole area of the polygon is covered, but the area cannot be too large or the while loop takes too long time.

Body:
The following algorithm will do nicely:

p = randpoint();
while(!IsInsidePolygon(p, poly)) {
  p = randpoint();
}

Big problem is choosing randpoint() so that the whole area of the polygon is covered, but the area cannot be too large or the while loop takes too long time.


答:
Your initial approach sounds like it would do what you need, but depending on how much time you could spend on finding a "good" point (not too close to an edge), you could gather several samples in various ways:

Let the intersecting ray hit the other side of the bounding box and look for pairs of intersections (1 & 2, 3 & 4, etc) that are farthest apart from one another.

Cast 2 or 4 rays: from corner to corner, from side to opposite side.

Title: Selecting a point inside a non-convex polygon

Body:
There are a lot of algorithms which will tell you whether or not a given point is found inside a polygon.

I'm looking to write an algorithm which, given a non-convex polygon, will return a point which is inside the polygon.

I don't need the point to be in any specific location inside the polygon, but I prefer to receive a point which isn't very close to an edge, but that is not a deal-breaker. It's there merely to mark that polygon's planar straight-line graph (PSLG) as an internal shape for use with Shewchuck's Triangle library for some complicated constrained Delaunay triangulations.

My initial thinking is:

Compute the bounding box

Cast a ray from one corner in the direction of the opposite corner, or from the center of a bounding box edge to the opposite edge center.

Then, a point exactly between the first and second intersection will
be inside the polygon.

Is there a better approach?


问:
Sourcecode license: free for personal use and modification but no public distibution
For one of my apps, I want to make the source code “open source” so that others might adapt the code to their personal needs or even contribute improvements, but I don’t want anybody else to publish “my app”. Furthermore, I still want to be able to sell the app at some time in the future.

Is there a usual license for this, like the GPL or similar?

I found similar questions from 2010 which say something about dual licensing, but maybe there is a license fitting my needs?

A commercial software but open and free for personal/edu. How to license?

Free for personal use license?

Open Source but not Free Software (or vice versa)

Software licensing: open source, no commerical, no derivatives

答:
First off, how big is your checkbook?

Putting a copyright notice on your stuff is one thing.  Enforcing your copyright is something else.  When (not if but WHEN) some scumbag steals your stuff, you're going to have to pay a lawyer to go after said scumbag.  This costs money.

Also note: In the US, for all practical purposes, to enforce a copyright, you must have registered the copyright with the government.  This costs a small amount of money.  The lawyer costs a lot more.  The money you pay for the lawyer will be WASTED if you didn't pay money to register the copyright FIRST.  This is the on-the-ground reality in the US.  Deal with it.

Having gotten all that out of the way...

The simplest answer is this: Put proper copyright notices on your stuff, with the magic incantation "All Rights Reserved", and put it on your website or FTP server or wherever.  Anyone is free to read copyrighted stuff.  Anyone is free to modify THEIR OWN PERSONAL COPY of copyrighted stuff.  (If this were not true, you would not be allowed to underline or highlight important stuff in your textbooks.)  The line is drawn at COPYING and redistributing the copyrighted stuff.

The thing is this: Once you put it out there, someone WILL attempt to rip it off and sell it, regardless of what your copyright notice says.  The world is full of scumbags, and not all of them are where your lawyers can reach.


答:
If you create a bounding circle instead of a bounding box, you can then select a random point on the circle, and cast rays at every X degrees across the circle (ie, like a chord, creating a fan of rays) to find the points.  Then, using whatever preferences you have for point selection, you can select the best point out of the points your 'sweeps' found.

But, I would recommend trying what you have come up with first, because that very well may be sufficient for your needs.


答: Given a polygon (P1, P2, ... Pn), construct triangles from the points adjacent to each vertex (P1 P2 P3), (P2 P3 P4), ... (Pn P1 P2),  and check if the center of the triangle is inside the polygon. </p>


答: Finding the point in a triangle which is furthest from its boundary is just finding the incentre. If you triangulate the polygon (not linear time, but not far off), you can then look for a "nice" triangle (e.g. the one with the largest shortest side) and take its incentre.</p>


问:
Web technologies on GUI apps
I developed many GUI applications for the Windows platform during my early professional career, and saw several GUI frameworks come, have whole magazines devoted to them, and then fade away. MFC is iconic.

Tasked with writing yet another GUI application, I starter researching cross-platform frameworks like Qt and WxWindows. I found the same steep learning curves I knew from before, and tooling doesn't help much in building a functional and elegant user interface because its clumsy and complicated.

But people are building beautiful and functional UIs on the Web all the time (look at this site!). The standards, the libraries, and the tools are certainly there.

My thought and my question: Why not write a GUI in which most of the UI is handled by an embedded browser? I already know that the Qt widgets support a large part of CSS and JavaScript, and programmers with good knowledge about web development are relatively easy to find, ..., so...

Have you done something like that before? What's your experience/advise?

A browser widget will likely support a subset of the functionality of mainstream browsers, but enough to produce a rich user interface using web technologies. There's the added advantage of the enormous simplifications possible when the web-stuff doesn't have to talk to a server to service UI requests.

My idea is not to embed a full-blown browser (yikes!). It is to enable the use of web technologies in GUI programming.

[Edit]

I haven't accepted an answer because the ones so far are suggestions about doing something else, and not about previous experience doing what I suggest. They're not even opinions or speculations about the pitfalls or benefits of doing it the suggested way, which is what I would expect in the unlikeliness that I'd be breaking new ground by using a browser widget to provide part of a GUIs interface. Think HTML, CSS, and limited JavaScript, with no Internet, no .Net or Java (or Air or Flex/Flash), no relational database; just executables, libraries, and templates that can be installed by copying them, and persistence to the user's home directory using the file system.

Some Addtional Related Questions

These are drawn from the answers so far:

User experience: Isn't the WebApp that runs StackExchange rich and intuitive enough?

User expectations: Hasn't the Web, and aren't portable gadgets (smartphones and tablets) moving the user experience away from the traditional GUI?

Could it be that there apps that must be GUI but benefit from being webified while other's don't?

答:
I have once been involved in creating such application. It was written in Qt and C++, but most of the windows were just containing a single QWebView which was then fed custom HTML. Some random notes:

It was somehow easier to develop than traditional web app, since you had to target only one HTML engine (one of most powerful, BTW).

It was somehow harder to develop than traditional web app, because manipulating HTML in C++ is unconvinient to say the least.

HTML lacks lots of GUI-related functionality, that is provided out-of-the box by traditional GUI toolkit. For example - I had to recreate tree view control in JavaScript, with lots of special cases as keyboard navigation, mouse selection. Such control is standard part of virtually every GUI framework.

Interacting with widgets is cumbersome. To get text of a Qt text entry, all you have to do is to call QString value = entry->text(). To get text of HTML entry inside QWebView we had to emit custom JavaSctipt that retrieves entry value, then unpack data from QVariant returned as result. Or something like that.

It was hard to keep Qt and HTML parts of application looking consistent. We ended with three[!] separate theming engines.

Performance was suboptimal and that application was a resource hog. It's hard to tell whether it was HTML to blame, though.

Title: Web technologies on GUI apps


问:
Is it okay to make coding style changes on an open source project that doesn't follow best practices?
Recently, I came across a number of open source Ruby (or majority of it was Ruby) projects on GitHub that when checked with a code analyzing tool like Rubocop, create a lot of offenses.

Now, most of these offenses include using double quotation marks instead of single quotes (when not interpolation), not following the 2 spaces per level rule, exceeding the 80 character line length rule, or using { and } for multi-line blocks.

[The] Ruby style guide recommends best practices so that real-world
  Ruby programmers can write code that can be maintained by other
  real-world Ruby programmers. ~ Source: Ruby Style Guide

Although they are small and easy to fix, is it appropriate to change the coding style of an open source project by fixing the offenses and making a Pull Request? I acknowledge that some projects, like Rails, do not accept cosmetic changes and some are just too large to "fix" all at once (Rails for example generates over 80,000 offenses when Rubocop is run - regardless, they have their own small set of coding conventions to follow when contributing). After all, the Ruby Style Guide is there for a reason together with tools like Rubocop.

People appreciate consistency so making these kinds of changes is kind of doing a good thing for the Ruby community in general, right?

[The author(s) of the Ruby Style Guide] didn't come up with all the
  rules out of nowhere - they are mostly based on my extensive career as
  a professional software engineer, feedback and suggestions from
  members of the Ruby community and various highly regarded Ruby
  programming resources, such as "Programming Ruby 1.9" and "The Ruby
  Programming Language". ~ Source: Ruby Style Guide

Isn't not following community coding style conventions and best practices basically encouraging bad practices?

答:
Taken from the Rubocop site itself (emphasis mine):

One thing has always bothered me as a Ruby developer - Python
  developers have a great programming style reference (PEP-8) and we
  never got an official guide, documenting Ruby coding style and best
  practices.

Please understand:

There is no Official Ruby Style Guide

I'm not saying that style guides are bad. But not only is there no official guide, but having a style guide is a choice that is made on a personal, project, team, company level. Style guides are, to use a psychology term, an "in-group social norm".

What does that mean for you? Well, if you aren't considered part of the in-group, that means anything you - or any other website says - is highly unlikely to hold any sway with the group. So if you aren't an active, respected contributor to that specific project then most likely your suggestions will be ignored, or will at best be a reminder of previous considerations about having a style guide. At worst it will be taken as an insult, or as an interloper or bikeshedder sticking their nose in where it doesn't belong.

Can't you just suggest a Style Guide?

In fact, that seems to be what you want to do: you believe in the value of style guides, you highly value consistency, and you want to evangelize for the dedication to unified style guidelines.

That's fine, so long as you are really clear that's what you are about and what you want to accomplish. If you believe in a particular Style Guide and believe it is The One True Style Guide, or at least better than whatever those lawless heathens are running around practicing, then that's fine too.

But what people do not appreciate is being told that their behavior does not conform to unofficial, non-binding, largely arbitrary rules that are from a source they do not consider a legitimate authority. When that's what you set out to do, or if merely that is what you are perceived to be doing, you'll get less of "the red carpet treatment", and more of the "angry natives with spears and a big boiling pot" treatment.


答:
Really good question. I always wondered about it myself for a few subsequent years in the past, I thought there was some legit reason behind this, but there really isn't.

I think the answer is rather simple, and a lot of answers are not really digging into the issue.

If your language allows to draw piexel on screen then it is 100% possible to create a gui framework based on it which will mimic Windows form controls looks & feel precisely.

Since Java is crossplatform its also entirely possible to make sure that based on actual running system type (Mac/Windows) UI would choose to look different on both platforms, matching the runtime platform style.

As you can see in XAML for example UI can be easily presented in very structured form and language. Choosing the "native" behaviours is also possible if time is taken to do this.

So it would be possible to create GUI framework which would allow Java developers to get applications which would look native on Mac and Windows.

So we get to Swing, thats just one GUI framework out of potential infinity of GUI frameworks which could be created for Java. It behaves how it was programmed, which doesn't follow the above process and you get weirdly looking apps on both systems. Thats the choice made by Swing developers, noone forced them to do this and to behave that way.

Title: Why is it hard to make a Java program 'appear native'?

Body:
Most Java applications don't look the same as C/C++ applications. Swing might have been designed on purpose to have a distincitve look, but based on what I've read, SWT for example tried to 'look native', and doesn't completley succeed.

My question is:

Why is it hard for the developers of the Java language to design a GUI system that copies exactly the look of native GUIs? What's different in native GUIs? Isn't it only a matter of designing buttons that look like 'native' buttons? Or does it go deeper than that?


问:
Mapping a list of optional values to an optional list of values
I have encountered the following pattern while programming in Haskell (but the pattern could occur in any language supporting lists, option types, and mapping of a function over a list). I have types a and b and a function

```<code>f :: a -> Maybe b
</code>```

Now I want to define a function that maps f on a list of type [a], but I am not interested to have a result of type [Maybe b]. Rather, I want to have Just [y1, ..., yn], if [f(x1), ..., f(xn)] == [Just y1, ..., Just yn], and Nothing otherwise (i.e. if f(xi) == Nothing for at least one i). So the result must be of type Maybe [b].

I solved this by using the following helper function:

```<code>combine :: Maybe b -> Maybe [b] -> Maybe [b]
combine me ml = do
                   l <- ml
                   e <- me
                   Just (e : l)
</code>```

and then

```<code>g :: (a -> Maybe b) -> [a] -> Maybe [b]
g f xs = foldr combine (Just []) (map f xs)
</code>```

So, for example, if I have

```<code>f x = if x > 0 then Just x else Nothing
xs0 = [1, 2, 3, 4]
xs1 = [-1, -2, 3, 4]
xs2 = [-1, -2, -3, -4]
</code>```

then

```<code>map f xs0 = [Just 1, Just 2, Just 3, Just 4]
g f xs0   = Just [1, 2, 3, 4]
map f xs1 = [Nothing, Nothing, Just 3, Just 4]
g f xs1   = Nothing
map f xs2 = [Nothing, Nothing, Nothing, Nothing]
g f xs2   = Nothing
</code>```

The solution with combine and foldr works, but I wanted to ask if you know of a more compact solution for turning a [Maybe a] into a Maybe [a] as described above.

答: The best way to approach this is to go to FP Complete's Hoogle and type in the signature you're looking for, (a -> Maybe b) -> [a] -> Maybe [b].  The first hit is a function called mapM which is exactly what you are looking for.  In fact it works for all Monads, not just Maybe.  (If you want to be even more general you can use traverse)


答:
You want a function with this signature:

```<code>(a -> Maybe b) -> [a] -> Maybe [b]
</code>```

Entering this into hoogle gives this possibility:

```<code>Prelude mapM :: Monad m => (a -> m b) -> [a] -> m [b]
</code>```

A look at the Hackage documentation for mapM says it is the same as:

```<code>mapM f = sequence . map f
</code>```

and that the definition of sequence is:

```<code>sequence       :: Monad m => [m a] -> m [a]
sequence ms = foldr k (return []) ms
            where
              k m m' = do { x <- m; xs <- m'; return (x:xs) }
</code>```

which is pretty much your foldr solution.

Title: Mapping a list of optional values to an optional list of values

Body:
I have encountered the following pattern while programming in Haskell (but the pattern could occur in any language supporting lists, option types, and mapping of a function over a list). I have types a and b and a function

```<code>f :: a -> Maybe b
</code>```

Now I want to define a function that maps f on a list of type [a], but I am not interested to have a result of type [Maybe b]. Rather, I want to have Just [y1, ..., yn], if [f(x1), ..., f(xn)] == [Just y1, ..., Just yn], and Nothing otherwise (i.e. if f(xi) == Nothing for at least one i). So the result must be of type Maybe [b].

I solved this by using the following helper function:

```<code>combine :: Maybe b -> Maybe [b] -> Maybe [b]
combine me ml = do
                   l <- ml
                   e <- me
                   Just (e : l)
</code>```

and then

```<code>g :: (a -> Maybe b) -> [a] -> Maybe [b]
g f xs = foldr combine (Just []) (map f xs)
</code>```

So, for example, if I have

```<code>f x = if x > 0 then Just x else Nothing
xs0 = [1, 2, 3, 4]
xs1 = [-1, -2, 3, 4]
xs2 = [-1, -2, -3, -4]
</code>```

then

```<code>map f xs0 = [Just 1, Just 2, Just 3, Just 4]
g f xs0   = Just [1, 2, 3, 4]
map f xs1 = [Nothing, Nothing, Just 3, Just 4]
g f xs1   = Nothing
map f xs2 = [Nothing, Nothing, Nothing, Nothing]
g f xs2   = Nothing
</code>```

The solution with combine and foldr works, but I wanted to ask if you know of a more compact solution for turning a [Maybe a] into a Maybe [a] as described above.

Body:
You want a function with this signature:

(a -> Maybe b) -> [a] -> Maybe [b]

Entering this into hoogle gives this possibility:

Prelude mapM :: Monad m => (a -> m b) -> [a] -> m [b]

A look at the Hackage documentation for mapM says it is the same as:

mapM f = sequence . map f

and that the definition of sequence is:

sequence       :: Monad m => [m a] -> m [a]
sequence ms = foldr k (return []) ms
            where
              k m m' = do { x <- m; xs <- m'; return (x:xs) }

which is pretty much your foldr solution.


问:
Understanding special Scala syntax
I can understand this:

```<code>List("one word", "another word") unzip (_ span (_ != ' '))
</code>```

But don't get what's happening here below in the span. span takes a predicate and I think the braces can be omitted as span is used inline and has only one parameter but why isn't there any _ and what is ' '.!=

```<code>List("one word", "another word") unzip (_ span ' '.!=)
</code>```

答:
In Scala, operators are just special-named methods. Here ' '.!= fetches but does not apply the != to the ' ' object. This method takes one parameter and returns a boolean value.

For any function f that takes a single argument, (x => f(x)) and f are equivalent expressions – so there is no need to wrap such a function into another lambda.

The span method takes a predicate, and partitions a sequence (here: String) into a prefix that satisfies the predicate, and a suffix that doesn't. Here we want to get the string up to the first space.

In the first line, we use the predicate (_ != ' '), more clearly (c => c != ' ').

We can now swap the arguments of the inequality “operator”, as this operation should be reflexive. We now have: (c => ' ' != c).

We can now use the explicit method call syntax: (c => ' '.!=(c)).

Next, we save that method in another variable:

```<code>val f: (Char => Boolean) = ' '.!=
...
(c => f(c))
</code>```

As stated above, f and (c => f(c)) are equivalent, therefore (_ != ' ') and ' '.!= must be equivalent too.

Title: Understanding special Scala syntax

Body:
In Scala, operators are just special-named methods. Here ' '.!= fetches but does not apply the != to the ' ' object. This method takes one parameter and returns a boolean value.

For any function f that takes a single argument, (x => f(x)) and f are equivalent expressions – so there is no need to wrap such a function into another lambda.

The span method takes a predicate, and partitions a sequence (here: String) into a prefix that satisfies the predicate, and a suffix that doesn't. Here we want to get the string up to the first space.

In the first line, we use the predicate (_ != ' '), more clearly (c => c != ' ').

We can now swap the arguments of the inequality “operator”, as this operation should be reflexive. We now have: (c => ' ' != c).

We can now use the explicit method call syntax: (c => ' '.!=(c)).

Next, we save that method in another variable:

val f: (Char => Boolean) = ' '.!=
...
(c => f(c))

As stated above, f and (c => f(c)) are equivalent, therefore (_ != ' ') and ' '.!= must be equivalent too.


答: Defining rectangles as point pairs allows you to reuse the point as a vertex for another shape.  Just a thought...</p>

Title: What's the idea behind defining rectangles with two points?

Body:
It's not that this doesn't make sense, but it just works out awkward 99% of the time.

Often in 2D graphics rectangles are initialized, stored and manipulated as a pair of points.  In no particular language,

```<code>class Rect:
   p1, p2: point
</code>```

It makes more sense to define a rectangle as two x values and two y values, like this:

```<code>class Rect
   xleft, xright: int
   ytop, ybottom: int
</code>```

With two points, if at some place in the source code you want to make use of the y value of the top, you'd have to say rect.p1.y  (hmmm, stop and think, is it p1 or p2) but with the four values as plain data members, it's clear and direct:  rect.ytop (no thinking required!)     The use of two points means that in dealing with the vertical, you have to tangle the horizontal; there's an extraneous relation between indepenent elements.

How did this two-point idea come about and why does it persists?  Does it have some benefit over bare x and y coordinates?

ADDED NOTE: This question is in the context of X-Y aligned rectangles, such as in windows managers and GUI toolkits, not in the context of arbitrary shapes in drawing and painting app.


问:
How to convince/prove my manager that a rewriting is needed rather than a refactoring
My manager wants me to refactor a gigantic amount of terribly-coupled, macroed, full of private namespace methods, hierarchy-perverted (even 10+ levels of inheritance) code which hasn't been (indeed) designed with a "whole-vision" concept.

I tried to explain to him that this code needs to be rewritten, not just refactored but he didn't listen and stated explicitly that I need to refactor it.. somehow.

I could dive into all the "dealing with legacy code" books but I think nothing useful would come out.

How can I convince him that a rewriting, instead of a refactoring, is actually needed?

答:
Before you attack the code, I would suggest starting with defining test cases and writing unit tests for them.

Unit tests are handy in a refactoring situation, as well as for a rewrite. They help with making sure that the required functionality stays correct, even when changing the code around.

When you decide to rewrite, you can run the unit tests against the original as well as the new code, making sure that functionality is not changed.

Unit tests will save your ass after multiple rounds of refactoring!


问:
A class with only methods
What's the name for a class that has only methods? There are no fields/properties. Just two methods with the ability to parse some file in two ways. I have named the class Parser, but it just doesn't seem right to have a class do only that. Or?

Should it be in a class ?

EDIT:

Dummy Example

```<code>class Parser
{
     public int parseMethod1(string file)
     {
         //parse & return
     }

     public string[] parseMethod2(string file)
     {
         //parse & return
     }
}
</code>```

How could I write an interface IParser which allowed me to have a subclass only implement one of the methods?

答:
An object-oriented design may actually be appropriate here, but both your parse methods belong in separate subclasses. You can use generics (type parameters) to achieve this. Something like:

```<code>interface IParser<T>
{
    public T parse(string);
}

class SomeParser : IParser<int>
{
    public int parse(string file)
    {
        ...
    }
}

class AnotherParser : IParser<string[]>
{
    public string[] parse(string file)
    {
        ...
    }
}
</code>```

Title: A class with only methods

Body:
An object-oriented design may actually be appropriate here, but both your parse methods belong in separate subclasses. You can use generics (type parameters) to achieve this. Something like:

interface IParser<T>
{
    public T parse(string);
}

class SomeParser : IParser<int>
{
    public int parse(string file)
    {
        ...
    }
}

class AnotherParser : IParser<string[]>
{
    public string[] parse(string file)
    {
        ...
    }
}


问:
Email Content creation | Proper design
Working on an E commerce application where we need to send so many email to customer like

Registration email

Forget Password

Order placed

There are many other emails that can be sent, I already have emailService in place which is responsible for sending email and It needs an Email object, Everything is working find, but I am struck at one point and not sure how best this can be done.

We need to create content so as it can be passed to emailService and not sure how to design this.

For example, in Customer registration, I have a customerFacade which is working between Controller and ServiceLayer, I just want to delegate this Email Content creation work away from Facade layer and to make it more flexible.

Currently I am creating Registration email content inside customerFacade and some how I am not liking this way, since that means for each email, I need to create content in respective Facade.

What is best way to go or current approach is fine enough?

答:
CustomerFacade? ServiceLayer? Is this Hybris?

Your instinct to move this away from your facade is correct. I would suggest an EmailRenderingService.

Pass a template and a Context object to a render method. You could use Renderer objects inside your service to render each different component in your email - like the text and images supplied from your CMS. These are contained in the template. The Context object contains the Customer and Order objects (etc) as I am sure is obvious.

But if this is hybris then look in the acceleratorservices extension where this is all done already. The three email examples you mention are exactly those provided out of the box. Named the same too, like all the classes in the question...

Title: Email Content creation | Proper design


问:
What design route should I take?
So I've taken on a project at work that I'm having a hard time attacking, and I'd love some feedback and suggestions.

I work for an online retail store where we have an old, +7k-line script that we use to create various product feeds (mostly for CSEs like Google Products, Pricegrabber, etc).  It's become a complete mess, mostly because each feed is slightly different and because there is almost no separation of concerns.

I've been tasked with refactoring it, a task I volunteered for with gusto, and pretty soon I need to come up with a design.  My main goal is to have a system that's easy to maintain, and easy to add new feeds as needed.  If performance suffers a bit that's not a huge concern, though increasing performance would be great if it doesn't interfere with the first two goals.

Until now, most of what I've worked on has been fairly linear and imperative; data comes in at the top and goes out at the bottom.  But because of the various feeds with various needs, I wonder if an object-oriented approach would be beneficial.  OO programming is still a bit of a mystery to me, so this problem has been a bit difficult to attack.

My basic idea is as follows; objects exist for each main concern (images, product descriptions, file handling, etc).  Then, each feed has an object (perhaps implementing an abstract class) that talks to the other objects, asking for the information it needs.  For instance, the Pricegrabber object feeds the Image object a list of products along with some parameters (maximum image size, etc) and the Image object returns a list of products with corresponding image urls.  This way, the Pricegrabber object doesn't know or care how the Image object finds its urls, or what mysql tables the Image object used or created; it just enters a list of products and gets a list of image urls.  Pricegrabber does this with every main object until the feed file is created.

Main questions:

Does this design pattern make sense?  Is there a better pattern I could use?

Does OO seem like overkill for what I'm trying to accomplish?

While we normally use Perl for our reports, would it be worth it to use PHP instead? If so, why? (I'd love to use Python or Ruby but IT has put the kabosh on that).

答:
Does this design pattern make sense?

What you've described is not a pattern, but rather kind of informal description of application architecture. You better don't think of it right now.

Try to create a domain vocabulary which describes all the things your application deals with:

feed (which has defferent fields),

product (which consists of photo, description, price, etc.),

customer/user,

order,

...

This would help you understand which classes/interfaces you'll probably need. Patterns would come next, as (and if) you need them.

If you're new to OOP, you shouldn't start using patterns right away. Just learn the basics and try to write the most simple code that does the job. Don't write the code that you don't understand (see Cargo cult programming).

Does OO seem like overkill for what I'm trying to accomplish?

Totally not an overkill. OOP is just a way of solving problems, not a technology. Of course, it can be used in a wrong way, but what you have now (solid piece of bare structural code) is much more wrong.

While we normally use Perl for our reports, would it be worth it to use PHP instead?

I don't have any experience with Perl, but I think it doesn't matter that much. Pick what you like more, just remember that PHP is simpler (IMO) and has larger community (which isn't necessarily better).

Title: What design route should I take?


答:
I believe it is mainly to establish uniformity between all shape primitives.

Sure you can define rectangle in many different ways, but how do you define a triangle, or a star, or a circle in a way that can use similar data structures?

All polygons can be defined by their points, with a short amount of logic to determine what to do with the points.

Graphics libraries primarily operate on these polygons in terms of vertices and edges, so points and the lines between them, all the calculations work on these two features, well that and facets, but that itself is just a function of the edges.


问:
Is using external repositories PCI-DSS compliant
We are considering using BitBucket rather than hosting our Git repositories internally. Does anyone know if this breaks any rules of PCI compliance? I haven't been able to find much information on this.</p>

答:
I'm basing this off of the 3.0 version (https://www.pcisecuritystandards.org/documents/PCI_DSS_v3.pdf) though I will admit that I might miss something (I'm most familiar with 2.0).

From the "highlights" pdf https://www.pcisecuritystandards.org/documents/DSS_and_PA-DSS_Change_Highlights.pdf there is something that catches my eye, though I can't find corresponding requirements in the DSS:

Enhanced requirements for system development processes including periodic security reviews, verifying integrity of source code, a versioning methodology, use of application threat-modeling techniques, and a formal authorization process before final release.

Though this is a proposed update I will note that the verification of integrity of the source code and versioning methodology are... interesting.

When working with an external host (or even an internal host), you likely need to validate that it was you that committed the code and not something else that someone did saying it was you.  I'll point you to What are the advantages and disadvantages of cryptographically signing commits and tags in Git? which goes into this a bit and in particular http://mikegerwitz.com/papers/git-horror-story.html

In theory, you are already doing this.  Working with external repositories this becomes even more critical that the source code can be verified.  I'm not sure why you are migrating to an external tool for hosting the code, though you might wish to investigate a more "polished" internal tool such as Atlassian Stash

Section 6 is where development issues are at hand and appears to be mostly unchanged from 2.0.  Mostly you need to verify that the code (6.3.2).  Having an external hosting, this becomes even more critical.

There is nothing in the requirements that say where you need to or can't host the source code.  The one thing to watch out for in this (that becomes many things) is the question of "is the server where the code is hosted a system component".  If it is, then a number of requirements get raised as things you need to watch for and be able to demonstrate to an auditor that you are doing things correctly.  These include 7.2, 8.1, 5.*.  You may need to be able to ask the provider "are you installing security patches within 30 days of availability."  Its not holding cardholder data, but... if they consider it a system component you've got some fun.

Depending on the familiarity with things of the auditor this could go many different ways (the ones familiar with it would want to verify that you're signing tags or commits and let it go at that, the ones that are tracking down every thing and can't tell a production source code hosting environment from a production cardholder data environment may want to see the audit access logs from BitBucket).  And that's where things may get difficult.

My reading of the PCI DSS 3.0 and remote hosting of the code:

You're good if you sign commits and/or tags and build only from these code lines.

You may need to alter how you work with git in order to do this (push branch and merge vs fork, tag, pull request -- I suspect the later would be considered to be better for explaining how it works to an auditor - that "verify integrity of source code and versioning methodology bit" in the proposed requirements)


问:
What are the advantages of next-iterator over this-iterator?
I don't work too often with Java/C# iterators directly but when I do I always wonder what was the reason to design iterators in "next" fashion.

In order to start you have to move iterator, in order to check if there is some data you have to check if there is next element.

More appealing concept for me is this-iterator -- it "starts" from the beginning, and you can check this state, let's say isValid. So the loop over entire collection would look like this:

```<code>while (iter.isValid())
{
  println(iter.current());
  iter.next();
}
</code>```

As you here in order to check if there is next element, you go there, and then you check if the state is valid.

YMMV but anyway -- is there any advantage of next-iterator (as in Java/C#) over this-iterator?

Note: this is conceptual question, about the design of the language.

答:
If there is some computation that needs to be done to compute each value having to get the next value before ever asking for the first value allows you to defer the processing of that first value beyond the construction of the iterator.

For example, the iterator could represent a query that has not yet been executed yet.  When the first item is requested, the database is queried for the results.  Using your proposed design, that computation would either need to be done upon construction of the iterator (which makes it harder to defer execution) or when calling IsValid, in which case it's really a misnomer, as calling IsValid would actually be getting the next value.

OwnerDisplayName: greenoldman

OwnerDisplayName: Servy


答:
I think an advantage of C#/.NET's MoveNext() model over Java's hasNext() model is that the former implies that some work may be done.  The hasNext() method implies a simple state check.  But what if you are iterating a lazy stream, and you have to go out to a database to determine whether there are any results?  In that case, the first call to hasNext() may be a long blocking operation.  The naming of the hasNext() method can be very misleading as to what's actually going on.

For a real world example, this design issue bit me when implementing Microsoft's Reactive Extensions (Rx) APIs in Java.  Specifically, for the iterator created by IObservable.asIterable() to function properly, the hasNext() method would have to block and wait for the next item/error/completion notification to arrive.  That's hardly intuitive: the name implies a simple state check.  Contrast that to the C# design, where MoveNext() would have to block, which is not an altogether unexpected result when you are dealing with a lazily evaluated stream.

My point is this: the "next-iterator" model is preferable to the "this-iterator" model because the "this-iterator" model is often a lie: you may be required to pre-fetch the next element in order to check the state of the iterator.  A design which communicates that possibility clearly is preferable, in my opinion.  Yes, Java's naming conventions do follow the "next" model, but the behavioral implications are similar to those of the "this-iterator" model.

Clarification: Perhaps contrasting Java and C# was a poor choice, because Java's model is deceptive.  I consider the most important distinction in the models presented by the OP to be that the "this-iterator" model decouples the "is valid" logic from the "retrieve current/next element" logic, while an ideal "next-iterator" implementation combines these operations.  I feel it is appropriate to combine them because, in some cases, determining whether the iterator's state is valid requires prefetching the next element, so that possibility should be made as explicit as possible.

I do not see a significant design difference between:

```<code>while (i.isValid()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.current()); // retrieve the element (may be slow!)
    i.next();
}
// ...and:
while (i.hasNext()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.next()); // retrieve the element (may be slow!)
}
</code>```

But I do see a meaningful difference here:

```<code>while (i.hasNext()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.next()); // retrieve the element (may be slow!)
}
// ...and:
while (i.moveNext()) { // fetch the next element if it exists (may be slow!)
    doSomething(i.current()); // get the element  (implied as fast, non-blocking)
}
</code>```

In both the isValid() and hasNext() examples, the operation that is implied to be a fast and non-blocking state check may in fact be a slow, blocking operation.  In the moveNext() example, most of the work is being done in the method you'd expect, regardless of whether you are dealing with an eagerly or lazily evaluated stream.

Title: What are the advantages of next-iterator over this-iterator?

Body:
I don't work too often with Java/C# iterators directly but when I do I always wonder what was the reason to design iterators in "next" fashion.

In order to start you have to move iterator, in order to check if there is some data you have to check if there is next element.

More appealing concept for me is this-iterator -- it "starts" from the beginning, and you can check this state, let's say isValid. So the loop over entire collection would look like this:

```<code>while (iter.isValid())
{
  println(iter.current());
  iter.next();
}
</code>```

As you here in order to check if there is next element, you go there, and then you check if the state is valid.

YMMV but anyway -- is there any advantage of next-iterator (as in Java/C#) over this-iterator?

Note: this is conceptual question, about the design of the language.

Body:
I think an advantage of C#/.NET's MoveNext() model over Java's hasNext() model is that the former implies that some work may be done.  The hasNext() method implies a simple state check.  But what if you are iterating a lazy stream, and you have to go out to a database to determine whether there are any results?  In that case, the first call to hasNext() may be a long blocking operation.  The naming of the hasNext() method can be very misleading as to what's actually going on.

For a real world example, this design issue bit me when implementing Microsoft's Reactive Extensions (Rx) APIs in Java.  Specifically, for the iterator created by IObservable.asIterable() to function properly, the hasNext() method would have to block and wait for the next item/error/completion notification to arrive.  That's hardly intuitive: the name implies a simple state check.  Contrast that to the C# design, where MoveNext() would have to block, which is not an altogether unexpected result when you are dealing with a lazily evaluated stream.

My point is this: the "next-iterator" model is preferable to the "this-iterator" model because the "this-iterator" model is often a lie: you may be required to pre-fetch the next element in order to check the state of the iterator.  A design which communicates that possibility clearly is preferable, in my opinion.  Yes, Java's naming conventions do follow the "next" model, but the behavioral implications are similar to those of the "this-iterator" model.

Clarification: Perhaps contrasting Java and C# was a poor choice, because Java's model is deceptive.  I consider the most important distinction in the models presented by the OP to be that the "this-iterator" model decouples the "is valid" logic from the "retrieve current/next element" logic, while an ideal "next-iterator" implementation combines these operations.  I feel it is appropriate to combine them because, in some cases, determining whether the iterator's state is valid requires prefetching the next element, so that possibility should be made as explicit as possible.

I do not see a significant design difference between:

while (i.isValid()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.current()); // retrieve the element (may be slow!)
    i.next();
}
// ...and:
while (i.hasNext()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.next()); // retrieve the element (may be slow!)
}

But I do see a meaningful difference here:

while (i.hasNext()) { // do we have an element?  (implied as fast, non-blocking)
    doSomething(i.next()); // retrieve the element (may be slow!)
}
// ...and:
while (i.moveNext()) { // fetch the next element if it exists (may be slow!)
    doSomething(i.current()); // get the element  (implied as fast, non-blocking)
}

In both the isValid() and hasNext() examples, the operation that is implied to be a fast and non-blocking state check may in fact be a slow, blocking operation.  In the moveNext() example, most of the work is being done in the method you'd expect, regardless of whether you are dealing with an eagerly or lazily evaluated stream.

OwnerDisplayName: Mike Strobel


答:
Re-writing a large project from scratch is often much harder than it looks like at first. Chances are if the code is a mess then the requirements and documentation are in even worse shape. You are going to be spending a lot of time coming up with requirements and figuring out how and why each part of the spaghetti code works. You are going to be constantly asking is this particular behavior a bug, a feature, or merely a convenience for the guy that wrote it.

From your managers perspective and hopefully from yours as well the ultimate goal is to create value for the business. After all as a professional we don't write code just to write code we write code in order to make money.

Something that you may not be looking at is the level of risk for the company and for your manager. If you start working on building from scratch and are not able to complete it for whatever reason the new half completed re-write could end up abandoned. Think of where this re-write would be in terms of priority if there is already a working version and the primary architect leaves in the middle of the project. Would there be a strong enough reason for the company with this upgrade?

Compare that to refactoring the existing code where there is still an actively developed version of the project. If you are no longer available to work on the project it won't be ideal but the risk is much lower.

For a manager to let you do a complete rewrite takes a lot of trust and is only occasionally worth doing even though rewriting is way more fun than cleaning up some one else's mess.

Title: How to convince/prove my manager that a rewriting is needed rather than a refactoring

Body:
My manager wants me to refactor a gigantic amount of terribly-coupled, macroed, full of private namespace methods, hierarchy-perverted (even 10+ levels of inheritance) code which hasn't been (indeed) designed with a "whole-vision" concept.

I tried to explain to him that this code needs to be rewritten, not just refactored but he didn't listen and stated explicitly that I need to refactor it.. somehow.

I could dive into all the "dealing with legacy code" books but I think nothing useful would come out.

How can I convince him that a rewriting, instead of a refactoring, is actually needed?


答:
I've been in the situation where a total rewrite is the best solution. Where the original code is a pile of poorly designed, little understood, hacked up by lazy programmers rubbish.

It's almost always possible to refactor such code from junk to useable code. But the problem is the amount of time it will take. Any series of refactoring's are going to involved extra cost. That being the time and code it takes to make each block of changes work with the legacy code that has not been changed yet. Another kicker is that it's not unusually for the original code to have originated out of the exact same thing you are looking at because someone started "refactoring" it and either did the minimum (read half arsed) or left before it was completed.

Most people support refactoring because their understanding of it is that it keeps things working and can be done piece meal. Therefore they perceive it as the "Safe" option. Mostly correct, but not always. They often choose it because they are too scared to take on a re-write.

Having said all that, you do need to fully understand what the application has to do. If you don't have a clear vision of this. Then it's unlikely that your re-write will be much better than the original.


问:
Requirement that code changes within release be reverse compatible with DB schema
I have recently come across a requirement related to our release/SDLC process that seems a little out of the ordinary to me so I am writing this to inquire whether this practice is common and, if not, whether our deployment process should be changed to eliminate a burdensome constraint.

I work for a small software shop that makes enterprise software (so not a household name) and we only have a handful yet very large customers.  It is a multi-server system management application running on Linux, DB backend, web front end, lots of async I/O and messaging.  We roll out upgrades approx. every 2-3 months and our customers deploy them using deb or rpm (depending on OS) packages we provide them.  All the customers deploy the app in a cluster environment with each server instance pointing to multiple database shards.

As of late I have been working on some legacy refactoring that significantly changed our DB schema.  To make a long story short, I reorganized how we store some data, split some tables into multiple new tables, reduced exposure to race conditions, and made corresponding code changes.

Just as I was getting ready to submit my changes, I was informed by our systems architect that, "due to the way our customers deploy upgrades" (each server and each database separately, one by one and can take days if not weeks, during which some of the servers must stay up), we cannot have tightly coupled changes and that all code upgrades must be reverse compatible with the database within a one release cycle period.  IOW, we cannot remove fields from database tables because in all customer configs all servers point to all database shards and we must enable a server to simultaneously work with one shard that is upgraded along with another that is not.

Now, I was befuddled and troubled by this requirement to say the least.  It seemed indicative of problems that the way our customers like to deploy changes (taking a long time), as well as their configuration, necessitates us to provide cumbersome dual functionality in parallel.  In my particular case, I was told that I need to keep the refactored fields in the old tables for legacy reads while writing into the new tables and then amalgamate the retrieved data.  This seems unnecessarily complex to me to say the least.

My questions are as follows:

Is this requirement unusual for the general configuration I described?  I have worked here around six months and I never worked for a product company before, always worked on site that made and deployed apps of their own (like a web site etc.).  Is this scenario common in software product companies?

Is this phenomenon of necessary reverse DB compatibility indicative of problems with the way our customers like to deploy our software?  To my knowledge, they apply our upgrades manually server by server, database by database while maintaining the production function.  Should they be using something like Puppet or Chef to deploy our upgrades in a much shorted timeframe?

How should I approach presenting a need to change all of this, it presents a developer inconvenience to say the least having to provide for this bifurcated functionality?

答:
No, it's not an unusual requirement.  It's common to expend significant effort to make upgrades as seamless as possible for the customer, sometimes even going so far as to purposely retain bugs that client software depends on.

I've had similar requirements even in environments where upgrades are done quickly with a script, even if the dual code is only in place for 15 minutes while the script runs.  It's very difficult to achieve zero downtime without such requirements.

Your job is to remove complexity for your customers.  Embrace that role.


问:
What would you add in this Software Development Project Checklist?
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time

答:
Toolchain setup - IDEs, CI server, code quality server, source control, webserver, databases, issue tracker etc.

Backups - What role does each person in the team have? What processes/modules does he 'own' and who is his backup?

(User-Acceptance) Test environment setup - Not only continuous integration w. unit tests, but integration tests to cover the really bad things, multiple platforms, application servers, VMs, etc.

Performance Tests setup - The earlier the better, since you will need historic data to answer "With which feature/milestone did the performance drop so badly?"

(End-User) Documentation outline - What is going to be in the documentation? What type(s) of documentation is needed?

Marketing channels - How are internal milestones and external releases being announced? Do you have a cool name for the software, a logo, colors, wording etc.?

Internal communication - How are peers from other teams going to be informed about changes? How is collaboration being done? Wiki? Access rights?

Quality Assurance people & process - Who is going to test what, how often and with what criteria?

Release process - When, how often, how, who is doing it, who is receiving the release etc.

Risk management - Worst-Case Scenario (from a project mgmt pov and from a runtime pov, e.g. 'customer is losing money because software failed at module X, what is the backup plan?)

Securing of the core development environment, e.g. virtualizing it for Escrow

Locations for formal and informal meetings

Training or intros for all the people, so they know what all the setup is, what each part is for and how they use it.

Identifying the caretaker and give him all the things (e.g. permissions) he needs to actually take care of when things go bad


问:
OO Design related questions in technical interviews
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```

答: I had been asked for coming out a design for a parking lot not too long ago. I wasn't given any use cases in the first place, but mentioned a couple later. I believe my design didn't fit what the interviewer's had in mind. I agree that any software design is only valid for a given use case. Back to this interview question, I believe that my interviewer didn't have any real world design experience. Those people believe that they know what they ask for. It is another story whether that is indeed true or not. </p>


答:
Negiotiate more man-days.

It is a rare event when people allocate enough initially.

[Later... re-negiotiate even more...]

Title: What would you add in this Software Development Project Checklist?

Body:
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time


问:
What is wrong with Java's generics?
I have seen several times on this site posts that decry Java's implementation of generics. Now, I can honestly say that I have not had any issues with using them. However, I have not attempted to make a generic class myself. So, what are your issues with Java's generic support?</p>

答:
The usual criticism is the lack of reification. That is to say objects at runtime do not contain information about their generic arguments (although the information is still present on fields, method, constructors and extended class and interfaces). This means that you could cast, say, ArrayList<String> to List<File>. The compiler will give you warnings, but it will also warn you if you take an ArrayList<String> assign it to an Object reference and then cast it to List<String>. The upsides are that with generics you probably shouldn't be doing the casting, performance is better without the unnecessary data and, of course, backward compatibility.

Some people complain that you cannot overload on the basis of generic arguments (void fn(Set<String>) and void fn(Set<File>)). You need to use better method names instead. Note that this overloading would not require reification, as overloading is a static, compile-time issue.

Primitive types don't work with generics.

Wildcards and bounds are quite complicated. They are very useful. If Java preferred immutability and tell-don't-ask interfaces, then declaration-side rather than use-side generics would be more appropriate.

Title: What is wrong with Java's generics?


问:
What to do with bugs that do not repro?
I have a tester that while testing will have an error occur (ok so far), but then he frequently reports it right away.  We (the developers) then later find that the tester has not tried to reproduce the issue and (when asked) cannot find a way to make it happen again.

Now these are still bugs, I don't want to ignore them.  But without repro steps I am kind of stuck.  Sometimes there is a stack trace (though frequently it is not useful because this is compact framework and there are no line numbers).  But when there is one I can take the stack trace and crack open the code and start guessing, but that does not lead to testable "fixes".

What do you do in scenarios like this?

答:
It sounds like this happens relatively frequently - which makes me wonder, is it because most of the bugs are genuinely hard to repro, or is it for some other reason that he's not trying?  Do you know why he isn't trying to reproduce the issue?  Is it because he doesn't realise how important it is to you?  Or is it perhaps that he has other pressures - a test manager who just wants him to get through the allotted tests quickly and throw the bugs over the wall, for example? Or maybe he's just not sure how to go about it?

I'd agree with others that working on better logging is a priority.  In the meantime, if you suspect that lack of tester skill/confidence may be an issue, then I really like this article from Danny Faught on bug isolation - you could point him at that for a start.

If the problem turns out to be due to management pressure - you have my sympathies, as that's a tough one to crack, especially if testers & programmers report to different managers and the managers aren't inclined to "help out" another team.

Title: What to do with bugs that do not repro?


问:
Algorithms: Find the best table to play (standing gambler problem)
Preface

This is not code golf. I'm looking at an interesting problem and hoping to solicit comments and suggestions from my peers. This question is not about card counting (exclusively), rather, it is about determining the best table to engage based on observation. Assume if you will some kind of brain implant that makes worst case time / space complexity (on any given architecture) portable to the human mind. Yes, this is quite subjective. Assume a French deck without the use of wild cards.

Background

I recently visited a casino and saw more bystanders than players per table, and wondered what selection process turned bystanders into betting players, given that most bystanders had funds to play (chips in hand).

Scenario

You enter a casino. You see n tables playing a variant of Blackjack, with y of them playing Pontoon. Each table plays with an indeterminate amount of card decks, in an effort to obfuscate the house advantage.

Each table has a varying minimum bet. You have Z currency on your person. You want to find the table where:

The least amount of card decks are in use

The minimum bet is higher than a table using more decks, but you want to maximize the amount of games you can play with Z.

Net losses, per player are lowest (I realize that this is, in most answers, considered to be  incidental noise, but it could illustrate a broken shuffler)

Problem

You can magically observe every table. You have X rounds to sample, in order to base your decision. For this purpose, every player takes no more than 30 seconds to play.

What algorithm(s) would you use to solve this problem, and what is their worst case complexity? Do you:

Play Pontoon or Blackjack ?

What table do you select ?

How many rounds do you need to observe (what is the value of X), given that the casino can use no more than 8 decks of cards for either game? Each table has between 2 and 6 players.

How long did you stand around while finding a table?

I'm calling this the "standing gambler problem" for lack of a better term. Please feel free to refine it.

Additional

Where would this be useful if not in a casino?

Final

I'm not looking for a magic gambling bullet. I just noticed a problem which became a bone that my brain simply won't stop chewing. I'm especially interested in applications way beyond visiting a casino.

答:
If I can concurrently examine all tables even while playing then:

Given that all games progress at the same speed for simplicity...(i could adjust for this)

```<code>
while(not satisfied with winnings)
 keepcurrenttable == 1 || Wait for positive count threshold on any one table
  if Z/(min bet)>%chance of win*payout
    next
  else
    Play hand according to standard counting rules.
  endif
if (%chance of win on another table*payout on another table > same for current) && Z/(min bet)>%chance of win*payout
  change tables
 elseif currenttable %chance of win*payout >
  keepcurrenttable=1
 else
  keepcurrenttable=0
 endif
next

</code>```

still some bugs in there and doesn't account for EVERYTHING, but you get where I'm going

there's a lot more to %chance of win

number of players should be minimally pertinent(more players == faster burning through decks)

does less players mean I can play more hands concurrently?(that would require heavier weight on player count)

additionally, count threshold could be defined with a risk appetite meter.

Body:
If I can concurrently examine all tables even while playing then:

Given that all games progress at the same speed for simplicity...(i could adjust for this)

while(not satisfied with winnings)
 keepcurrenttable == 1 || Wait for positive count threshold on any one table
  if Z/(min bet)>%chance of win*payout
    next
  else
    Play hand according to standard counting rules.
  endif
if (%chance of win on another table*payout on another table > same for current) && Z/(min bet)>%chance of win*payout
  change tables
 elseif currenttable %chance of win*payout >
  keepcurrenttable=1
 else
  keepcurrenttable=0
 endif
next

still some bugs in there and doesn't account for EVERYTHING, but you get where I'm going

there's a lot more to %chance of win

number of players should be minimally pertinent(more players == faster burning through decks)

does less players mean I can play more hands concurrently?(that would require heavier weight on player count)

additionally, count threshold could be defined with a risk appetite meter.


问:
How do Text User Interfaces (TUI) work?
I have recently been assigned to port an old COBOL program. I am used to GUIs, and I can't understand how a TUI works. I searched a lot through Google but couldn't find something.

I knew that console applications could output line by line, but how are colors etc. drawn to the terminal screen? How all this stuff is being drawn?
Do terminals support it somehow? Is there a standard? I am really confused.

答:
Don't worry, there are hundreds of standards to choose from :)

I am sadly more comfortable with text- and console-based applications than their older graphical window brethren.  Too many days on FidoNet I fear.

The very first thing I would do is learn a few VT100 codes from the old Digital company.  You may never write applications in VT100 codes (likely advise against it), but it is a very good and simple introduction to controlling the console matrix.

Libraries such as curses wrap these control codes (and many other style terminal codes) and abstract them so that users can login via their own terminals.  Things like VT100 can even do remote (local) printing with which we still struggle today in RDP.

To make things worse for you, IBM systems use not line- or character-based control, but screen- and block-based protocols.  Examples are the 3270 and 5250 terminal protocols which for the lack of a better comparison act in the request|response architecture think HTTP.  As capable as these are, they are a true PITA IMNSHO with which to work and should be their own separate question.

Worse than that would be writing a console application in a DOS/Windows world.  Do reply with your target development platform.

Title: How do Text User Interfaces (TUI) work?


问:
What's the idea behind defining rectangles with two points?
It's not that this doesn't make sense, but it just works out awkward 99% of the time.

Often in 2D graphics rectangles are initialized, stored and manipulated as a pair of points.  In no particular language,

```<code>class Rect:
   p1, p2: point
</code>```

It makes more sense to define a rectangle as two x values and two y values, like this:

```<code>class Rect
   xleft, xright: int
   ytop, ybottom: int
</code>```

With two points, if at some place in the source code you want to make use of the y value of the top, you'd have to say rect.p1.y  (hmmm, stop and think, is it p1 or p2) but with the four values as plain data members, it's clear and direct:  rect.ytop (no thinking required!)     The use of two points means that in dealing with the vertical, you have to tangle the horizontal; there's an extraneous relation between indepenent elements.

How did this two-point idea come about and why does it persists?  Does it have some benefit over bare x and y coordinates?

ADDED NOTE: This question is in the context of X-Y aligned rectangles, such as in windows managers and GUI toolkits, not in the context of arbitrary shapes in drawing and painting app.

答:
I always liked defining a rectangle as a point + width and height, where the point is the upper-left corner of the rectangle.

```<code>class Rect {
  float x, y;
  float width, height;
}
</code>```

And then add whatever methods you need to fetch the other metrics. Like the Java version

Body:
I always liked defining a rectangle as a point + width and height, where the point is the upper-left corner of the rectangle.

class Rect {
  float x, y;
  float width, height;
}

And then add whatever methods you need to fetch the other metrics. Like the Java version


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答:
The problem with optional arguments is that people tend to just tuck on more and more (and more) arguments to the function instead of extracting relevant code into a new function. This is taken to the extreme in php. For instance:</p>

```<code>bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC
                      [, mixed $arg = SORT_REGULAR [, mixed $... ]]] )
</code>```

Body:
The problem with optional arguments is that people tend to just tuck on more and more (and more) arguments to the function instead of extracting relevant code into a new function. This is taken to the extreme in php. For instance:

bool array_multisort ( array &$arr [, mixed $arg = SORT_ASC
                      [, mixed $arg = SORT_REGULAR [, mixed $... ]]] )


答:
Surely if you define your rectangle as:

```<code>class Rect
{
    Point bottomLeft;
    Point topRight;
}
</code>```

then you know straight away which point is which.

Even better would be to add extra properties that allowed you to manipulate the rectangle in which ever ways you needed for your application. These would simply update the underlying data structure.

By adding a transformation to the shape you can orient your rectangle any way you'd like. You'd still need an axis aligned bounding box for quick accept/reject checks :)

However, if your model allows rectangles in any orientation without applying a transformation then "bottom left" and "top right" have no meaning, which leads back to "p1" and "p2" (or something equivalent).

Body:
Surely if you define your rectangle as:

class Rect
{
    Point bottomLeft;
    Point topRight;
}

then you know straight away which point is which.

Even better would be to add extra properties that allowed you to manipulate the rectangle in which ever ways you needed for your application. These would simply update the underlying data structure.

By adding a transformation to the shape you can orient your rectangle any way you'd like. You'd still need an axis aligned bounding box for quick accept/reject checks :)

However, if your model allows rectangles in any orientation without applying a transformation then "bottom left" and "top right" have no meaning, which leads back to "p1" and "p2" (or something equivalent).


问:
What's the best way to explain branching (of source code) to a client?
The situation is that a client requested a number of changes about 9 months ago which they then put on hold with them half done.  They've now requested more changes without having made up their mind to proceed with the first set of changes.  The two sets of changes will require alterations to the same code modules.

I've been tasked with explaining why them not making a decision about the first set of changes (either finish them or bin them) may incur additional costs (essentially because the changes would need to be made to a branch then if they proceed with the first set of changes we'd have to merge them to the trunk - which will be messy - and retest them).

The question I have is this:

How best to explain branching of code to a non-technical client?

答:
You are building a truck.  You think you want to use it for towing, so you want a bigger engine and brakes.  Brakes are cheaper so you put those in first.  No wait....You might not need to tow.  Pause engine choice.

You now want better gas mileage so it needs to be lighter you swap out some components so it's lighter, but if you can't decide on the heavy engine/towing or not.  The big brakes might now cause it to break traction and skid out of control.  If we take out the big brakes the truck might not stop.

Either situation poses a problem.  To finish end tasks, dependent tasks should be complete or double/triple work is generated.

Moving forward at all creates double work.  Double work costs money or time. More money == over budget / more time == outside of time-line.

If you can make a logical problem physical more people understand it...the money relation never hurts.

IMO, you get to try and explain cost impact once.  If they don't get it, you point out that new deliverables require contract renegotiation.  Are you nearing a payment milestone?  That could be it too, they want to force either you eating the feature, or contract renegotiation failure so they can move to another development team with the progress they have and not pay for it.


答:
Typically I note that it is not reproducible, but leave it open until that batch of testing or iteration is complete.

If it has not been reproduced by that point it is closed, but can be reopened if it is encountered again.

Title: What to do with bugs that do not repro?

Body:
I have a tester that while testing will have an error occur (ok so far), but then he frequently reports it right away.  We (the developers) then later find that the tester has not tried to reproduce the issue and (when asked) cannot find a way to make it happen again.

Now these are still bugs, I don't want to ignore them.  But without repro steps I am kind of stuck.  Sometimes there is a stack trace (though frequently it is not useful because this is compact framework and there are no line numbers).  But when there is one I can take the stack trace and crack open the code and start guessing, but that does not lead to testable "fixes".

What do you do in scenarios like this?


答:
Well, the first task is to have a reproducible test system. Your tester must have a well-defined process - automatic if at all possible.

Have these three conditions:

Same binary

Same steps

Same machine

If the bug sporadically appears with the above 3 conditions, begin to isolate further. Consider each level of the system stack and its configuration.

One way to detect memory management errors is to run the program on multiple OSs with multiple compilers. Valgrind can also help.

However, typically parallel systems are liable to induce non-repro bugs. Things like buffer sizes and processing speeds, asynch io, database locks, variable memory write interleavings; all of those can generate issues. And so forth and so on.

Title: What to do with bugs that do not repro?


答:
Actually, a rectagle isn't defined by 2 points. A rectangle can only be defined by two points if it is parallel to the axes.

There are several ways to represent rectangles that are parallel to the axes:

Two diagonally opposite points

One corner point, height and width

Centre point, half height and width (uncommon, but sometimes useful).

As two X coordinates and two Y coordinates

For (1), many libraries use a convention to determine which two points are used - topLeft and bottomRight, for example.

The choice of representation may be driven by the original purpose of the rectangle definition, but I imagine that it often arbitrary. The representations are equivalent in the information that they carry. They do, however, differ in the ease with which properties of the rectangle may be calculated and the the convenience with which operations can be performed on the reectangle.

Benefits of definition (1) over others include:

Consistency of API with other polygons, lines etc.

topLeft, bottomRight can be passed to any method that accepts points

Methods of Point class can be called on topLeft, bottomRight

Most properties can be derived easily, eg. bottomLeft, topRight, width, height, centre, diagonal length, etc.


答:
In two dimensions, storing a rectangle as two points is clearer than defining a particular corner and a width and height - consider negative width or height, or the calculations required to determine each option from the other.

Performing rotations on a rectangle defined by points is also much simpler than one defined with a point plus width and height.

I'd expect encapsulation to make this differentiation unimportant as a user of the class.

A rectangle should be defined as three points to be well defined in 3 dimensions.  I'm not entirely sure of the requirement for defining a rectangle in 4 or more dimensions.


问:
Software on Budget and on time?
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?

答:
We built a web based multiple listing service application. The first one took the most time but the idea was to build a solid app that could be cloned quite easily. While a fair amount of R & D went into the first one, we were able to turn them out fairly quickly and did make a profit on each one we sold.

I don't work there anymore but it's still a good application.

Webfodder MLS Application

Title: Software on Budget and on time?


答: I don't like it because we have thrown out a potential degree of freedom, which essentially allows for an arbitrary rotation. A general 2D rectangle has five unknowns (degrees of freedom). We could specify them as the coordinates of a point, the lengths of the two sides that form a vertex with this point, and the angle from the horizontal of the first line (the other being assumed to have an angle 90 degrees greater). An infinite number of other possibilities could also be used, but there are five independent quantities that must be specified. Some choices will lead to easier algebra than others, depending upon what is done with them.</p>


问:
What is Configuration Management?
In all projects that I have been involved with that have had input from an outside consultant the question has been asked about what sort of Configuration Management we were using. In none of these cases has the consultant been able to define Configuration Management. So what is it?</p>

答: Configuration Management encompasses "everything else" that's not directly related to writing code. So it's how you manage releases, how you manage and triage bug reports and feature suggestions, how you perform your builds and so on. It often also includes how your source code is managed (e.g. what version control you use, branching strategies, how you [possibly] manage multiple concurrent "releases" etc).</p>

Title: What is Configuration Management?


Body:
Pa(x,y)*-----------------------------------*Pb(x,y)
       |                                   |
       |                                   |
       |                                   |
       |                                   |
       |                                   |
       |                                   |
Pc(x,y)*-----------------------------------*Pd(x,y)

We can define both Pb & Pc thus:

Pb(Pd(x),Pa(y))

and

Pc(Pa(x),Pd(y))

So there is no need to define all four points due to symmetry


答:
Have you considered that it is less error prone?

If you use (Point1, Point2) it is then very clear what you are specifying. If you provide 2 points, then the only possible error is that the user has mixed up their x and y when constructing the points as the order of the points doesn't matter.

If you supply 4 integers, then if someone isn't paying attention, they may supply (x1,x2,y1,y2) when you wanted (x1,y1,x2,y2) or vice versa. Also, some APIs such as WCF's Rect structure define a rectangle as (x, y, width, height) which could then cause confusion over what (1, 2, 3, 4) means. Is that (x, y, w, h) or (x1, y1, x2, y2) or (x1, x2, y1, y2)?

All in all, (Point1, Point2) seems a bit safer to me.


答:
Optional parameters are a great way to make simple things simple and complicated things possible simultaneously.  If there's a clear reasonable default that most users will want, at least in quick and dirty use cases, then they should not have to write boilerplate to manually specify it every single time they call your function.  On the other hand, if people might have a good reason for wanting to change it, then it needs to be exposed.

Using a class is IMHO a terrible solution, as it's verbose, inefficient and inconsistent with the typical mental model of what a class does.  A function is the perfect abstraction for a verb, i.e. doing something and returning.  A class is the right abstraction for a noun, i.e. something that has state and can be manipulated in several ways.  If the former should be the API user's mental model, then don't make it a class.

Title: Are optional parameters helpful or a hindrance to application maintenance?

Body: As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>


问:
Where is Smalltalk-80 best used?
I want to know in which applications/programming domain are most suitable for Smalltalk. Could anyone please provide me some useful links that could answer my query?

Through googling I learned that some companies use it for:

logistics and foreign trade application
desktop, server and script development
data processing and logistics, scripts and presentations
but I cant find documents/research papers that can tell me which programming domain Smalltalk-80 (or Smalltalk) is best suited.

Some of the programming domains are: - Artificial intelligence reasoning - General purpose applications - Financial time series analysis - Natural language processing - Relational database querying - Application scripting - Internet - Symbolic mathematics - Numerical mathematics - Statistical applications - Text processing - Matrix algorithms

I hope you guys can help me. I am doing this for my case study. Thanks in advance.

答:
Smalltalk is a general-purpose programming language that is used for all sorts of stuff.

A lot of consulting companies treat Smalltalk as their "secret weapon" that allows them to outbid and outperform their competitors, for example. Some of them even go so far as to develop their own Smalltalk implementations.

E.g. Smalltalk/X is the in-house platform for eXept Software. In a similar vein, Lesser Vision-Smalltalk is the secret weapon of Lesser Software. They actually use it for Windows desktop applications.

It is widely used in the financial industry for modeling complex financial products such as derivatives, swaps, etc. So widely, in fact, that some Smalltalk community leaders have jokingly accepted full responsibility for the 2007 meltdown.

Smalltalk excels the more complex the domain is. Trendly uses an interesting mix of languages and its lead developer, Avi Bryant, gave a good description of what the particular languages are useful for. He said something like "we use Smalltalk for the thinking, Java for the muscle, ECMAScript for the pretty face and Ruby to glue it all together". So, the complex statistical models and algorithms are in Smalltalk, the actual brute-force calculations are done in Java and the results are rendered dynamically on the client-side in ECMASCript.

OwnerDisplayName: njay

Title: Where is Smalltalk-80 best used?


答:
It's completely arbitrary. You need four pieces of information to draw a rectangle. The library designer(s) decided to represent it with two points (each with an x-y coordinate), but could easily have done it with x/y/w/h or top/bottom/left/right.

I suppose the OP's real question is: why was this particular choice made?


答:
I think other answers have said this to some degree, but not very clearly.  One of the problems with generics is losing the generic types during the reflection process.  So for example:

```<code>List<String> arr = new ArrayList<String>();
assertTrue( ArrayList.class, arr.getClass() );
TypeVarible[] types = arr.getClass().getTypedVariables();
</code>```

Unfortunately, the returned types can't tell you that arr's generic types are String.  It's a subtle difference, but it's important.  Because arr is created at runtime the generic types are erased at runtime so you can't figure that out.  As some stated ArrayList<Integer> looks the same as ArrayList<String> from a reflection standpoint.

This might not matter to the user of Generics, but let's say we wanted to create some fancy framework that used reflection to figure out fancy things about how the user declared an instance's concrete generic types.

```<code>Factory<MySpecialObject> factory = new Factory<MySpecialObject>();
MySpecialObject obj = factory.create();
</code>```

Let's say we wanted a generic factory to create an instance of MySpecialObject because that's the concrete generic type we declared for this instance.  Well Factory class can't interrogate itself to find out the concrete type declared for this instance because Java erased them.

In .Net's generics you can do this because at runtime the object knows it's generic types because the compiler complied it into the binary.  With erasures Java can't do this.

Title: What is wrong with Java's generics?

Body: I have seen several times on this site posts that decry Java's implementation of generics. Now, I can honestly say that I have not had any issues with using them. However, I have not attempted to make a generic class myself. So, what are your issues with Java's generic support?</p>

Body:
I think other answers have said this to some degree, but not very clearly.  One of the problems with generics is losing the generic types during the reflection process.  So for example:

List<String> arr = new ArrayList<String>();
assertTrue( ArrayList.class, arr.getClass() );
TypeVarible[] types = arr.getClass().getTypedVariables();

Unfortunately, the returned types can't tell you that arr's generic types are String.  It's a subtle difference, but it's important.  Because arr is created at runtime the generic types are erased at runtime so you can't figure that out.  As some stated ArrayList<Integer> looks the same as ArrayList<String> from a reflection standpoint.

This might not matter to the user of Generics, but let's say we wanted to create some fancy framework that used reflection to figure out fancy things about how the user declared an instance's concrete generic types.

Factory<MySpecialObject> factory = new Factory<MySpecialObject>();
MySpecialObject obj = factory.create();

Let's say we wanted a generic factory to create an instance of MySpecialObject because that's the concrete generic type we declared for this instance.  Well Factory class can't interrogate itself to find out the concrete type declared for this instance because Java erased them.

In .Net's generics you can do this because at runtime the object knows it's generic types because the compiler complied it into the binary.  With erasures Java can't do this.