答:
I am a strong believer in keeping business logic out of the database as much as possible.  However, as my company's performance developer, I appreciate that sometimes it's necessary to achieve good performance.  But I think it is necessary far less often than people claim.

I dispute your pros and cons.

You claim that it centralizes your business logic.  On the contrary, I think it decentralizes it.  In a product that I currently work on, we use stored procedure for a lot of our business logic.  Many of our performance issues come from calling functions repeatedly.  For instance

```<code>select <whatever>
from group g
where fn_invoker_has_access_to_group(g.group_id)
</code>```

Problem with this approach is that it generally (there may be cases where this is false) forces the database to run your function N times, once per row.  Sometimes that function is expensive.  Some databases support function indexes.  But you can't index every possible function against every possible input.  Or can you?

A common solution to the above problem is to extract the logic from the function and merge it into the query.  Now you have broken encapsulation and duplicated logic.

Another issue I see is calling stored procedures in a loop because there is no way to join or intersect stored proc result sets.

```<code>declare some_cursor
while some_cursor has rows
    exec some_other_proc
end
</code>```

If you pull the code from the nested proc out, then you again decentralize.  Therefore, you are forced to choose between encapsulation and performance.

In general, I find that databases are bad at:

Computation

Iteration (they are optimized for set operations)

Load balancing

Parsing

Databases are good at:

Locking and unlocking

Maintaining data and their relationships

Ensuring integrity

By taking expensive operations like loops and string parsing and keeping them in your app tier, you can horizontally scale your application to get better performance.  Adding multiple app servers behind a load balancer is usually far cheaper than setting up database replication.

You are correct, however, that it decouples your business logic from your application's programming language, but I don't see why that is an advantage.  If you have a Java app, then you have a Java app.  Converting a bunch of Java code into stored procedures doesn't change the fact that you have a Java app.

My preference is to keep database code focused on persistence.  How do you create a new widget?  You must insert into 3 tables and they must be in a transaction.  That belongs in a stored procedure.

Defining what can be done to a widget and the business rules for finding widgets belongs in your application.

Body:
I am a strong believer in keeping business logic out of the database as much as possible.  However, as my company's performance developer, I appreciate that sometimes it's necessary to achieve good performance.  But I think it is necessary far less often than people claim.

I dispute your pros and cons.

You claim that it centralizes your business logic.  On the contrary, I think it decentralizes it.  In a product that I currently work on, we use stored procedure for a lot of our business logic.  Many of our performance issues come from calling functions repeatedly.  For instance

select <whatever>
from group g
where fn_invoker_has_access_to_group(g.group_id)

Problem with this approach is that it generally (there may be cases where this is false) forces the database to run your function N times, once per row.  Sometimes that function is expensive.  Some databases support function indexes.  But you can't index every possible function against every possible input.  Or can you?

A common solution to the above problem is to extract the logic from the function and merge it into the query.  Now you have broken encapsulation and duplicated logic.

Another issue I see is calling stored procedures in a loop because there is no way to join or intersect stored proc result sets.

declare some_cursor
while some_cursor has rows
    exec some_other_proc
end

If you pull the code from the nested proc out, then you again decentralize.  Therefore, you are forced to choose between encapsulation and performance.

In general, I find that databases are bad at:

Computation

Iteration (they are optimized for set operations)

Load balancing

Parsing

Databases are good at:

Locking and unlocking

Maintaining data and their relationships

Ensuring integrity

By taking expensive operations like loops and string parsing and keeping them in your app tier, you can horizontally scale your application to get better performance.  Adding multiple app servers behind a load balancer is usually far cheaper than setting up database replication.

You are correct, however, that it decouples your business logic from your application's programming language, but I don't see why that is an advantage.  If you have a Java app, then you have a Java app.  Converting a bunch of Java code into stored procedures doesn't change the fact that you have a Java app.

My preference is to keep database code focused on persistence.  How do you create a new widget?  You must insert into 3 tables and they must be in a transaction.  That belongs in a stored procedure.

Defining what can be done to a widget and the business rules for finding widgets belongs in your application.


问:
Is this a Proper "Rule" for Identifying the "Big O" Notation of an Algorithm?
I've been learning more about Big O Notation and how to calculate it based on how an algorithm is written. I came across an interesting set of "rules" for calculating an algorithms Big O notation and I wanted to see if I'm on the right track or way off.

Big O Notation: N

```<code>function(n) {
    For(var a = 0; i <= n; i++) { // It's N because it's just a single loop
        // Do stuff
    }
}
</code>```

Big O Notation: N2

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        For(var c = 0; i <= b; c++) { // It's N squared because it's two nested loops
            // Do stuff
        }
    }
}
</code>```

Big O Notation: 2N

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        // Do stuff
    }
    For(var c = 0; i <= b; c++) { // It's 2N the loops are outside each other
        // Do stuff
    }
}
</code>```

Big O Notation: NLogN

```<code>function(n) {
    n.sort(); // The NLogN comes from the sort?
    For(var a = 0; i <= n; i++) {
        // Do stuff
    }
}
</code>```

Are my examples and the subsequent notation correct? Are there additional notations I should be aware of?

答:
Recall that this is an approximate representation of run-time.  The "rule-of-thumb" is approximate because it is imprecise but gives a good first-order approximation for evaluation purposes.

The actual run-time will depend on how much heap-space, how fast is the processor, instruction set, use of prefix or post-fix increment operators, etc., yadda.  Proper run-time analysis will allow determination of acceptance but having knowledge of the basics allows you to program right from the beginning.

I do agree you are on the right track to understanding how Big-O is rationalized from a textbook to a practical application.  That may be the difficult hurdle to overcome.

Asymptotic growth-rate becomes important on large data sets and large programs so for typical examples you demonstrate it is not as important to proper syntax and logic.

ContentLicense: CC BY-SA 3.0


问:
How to see bits of an integer in Visual Studio
As far as I know it is not possible to see the bits of an integer in Visual Studio, you can see variables in decimal or hexadecimal format in the Locals and Watch windows in the debugger.

Why is this limitation in place and are there any tools/addins to see integers as bits?

答:
I can't speak for the Visual Studio team, but my guess is that it wasn't a limitation that was specifically put in place. Your premise assumes this is the case. It was likely rather a feature that needed to be added and it was determined to be low priority.

It's not clear to me what you're referring to in order to suggest a workaround. Do you mean the Watches window? If so, you can write a function that returns a string of the bits and use that in the Watches window. It's a little awkward, but this would give you the functionality you desire.

EDIT: Ah. You can write a function sort of like such:

```<code>namespace util {
    template<typename TInteger>
    std::string to_binary(TInteger value) {
        std::bitset<sizeof(TInteger) * 8> bs(value);
        return bs.to_string();
    }
}
</code>```

Standard disclaimer: I don't currently have access to a compiler so this may not compile or work, but it should definitely get you started in the right direction. It may be the case that the templates and the Watches window don't mix well together, but it's fairly trivial to write specific functions for each type.

Usage assuming it's included in the translation unit would be fairly simple: util::to_binary(55) or whatever the case may be in the Watches window.

Body:
I can't speak for the Visual Studio team, but my guess is that it wasn't a limitation that was specifically put in place. Your premise assumes this is the case. It was likely rather a feature that needed to be added and it was determined to be low priority.

It's not clear to me what you're referring to in order to suggest a workaround. Do you mean the Watches window? If so, you can write a function that returns a string of the bits and use that in the Watches window. It's a little awkward, but this would give you the functionality you desire.

EDIT: Ah. You can write a function sort of like such:

namespace util {
    template<typename TInteger>
    std::string to_binary(TInteger value) {
        std::bitset<sizeof(TInteger) * 8> bs(value);
        return bs.to_string();
    }
}

Standard disclaimer: I don't currently have access to a compiler so this may not compile or work, but it should definitely get you started in the right direction. It may be the case that the templates and the Watches window don't mix well together, but it's fairly trivial to write specific functions for each type.

Usage assuming it's included in the translation unit would be fairly simple: util::to_binary(55) or whatever the case may be in the Watches window.


问:
Is it OK to have a team with same abilities but different skill levels?
I believe that in an ideal team, members should have different but complementary abilities. But is that true about software development teams?

As an example we are a small team of 5. We almost have the same abilities and interests but with different levels of skills. Regarding such situation I think we don't cover our teammates' weaknesses.

Is there any pattern to follow to manage and improve such team?

Should I setup a team with different abilities and interests to maximize the performance and productivity?

-- EDIT --

Our current team has a specific lifetime. We work together in a per-project manner. In another word we may change the team arrangement for each project depending on the project and developers situation. Actually we've provided a sort of floating situation.

In short, we are a network of developers rather than a fixed-size development team.

答:
I think your initial premise is invalid. What matters is that you cover the needed skills. Ideal in one situation may be disastrous in another. It also matters that you have someone avaliable who can step in when someone else is out, so each necessary skill should have at least one really strong person and someone else with enough knowledge to fix emergencies if a person is out unexpectedly.

There are different ways to cover the needed skills and most of them work just fine depending on the situation. In a C# shop that uses SQL Server as the database, you need a different mix of skills than in a place where every project uses a new set of tools. If you do work that is highly specializzed in several different ways, you may need to hire specialists. If the team is large, you may need a mix of generalists and specialists. If you are expecting to grow rapidly, you may want to have a mix of senior and junior people being mentored to become the senior people as you expand your work force. If your workload varies a lot through the year, you might want a mix of full-time and part-time or permanent and contract workers. A team of people doing embedded systems may need a narrower skill set that everyone on the team has and a team of web devlopers might need a mix of  web designers, UI specialists and backend application developers who cover a huge variety of languages. A team doing Enterprise devloepment might require more specialists such as Big data specialists, BI specialists, reporting specialists, DBAs, QA personnel  as well as application programmers specializing in two or three main languages, architects, etc. And of course the larger the group, the more you can afford to (and by the nature of the workload, need to) specialize rather than everyone having the same rough set of skills. You might even need people with specific domain knwoldge (espcially in medical applications and finance) that is more critical that the specific technical skills.


问:
Deleting Lookup Item
I was wonder what people do in this situation.

You have an admin area of a system where you let users define a list of values they want to see in a dropdowns across the system.

What do you do in your application is a user wants to delete this option?

What do you do with data records which already use this value?

答: One option is to implement a "no longer in use" flag.  Existing records remain the same (& the value continues to be visible where it was used), but it's no longer available as an option on the dropdowns.</p>

Title: Deleting Lookup Item


问:
Why is SIT called SIT when it serves for system testing?
I should define a testing strategy and environments and I have encountered rather terminology issue (but might well be my fault) so I hope someone will correct me here.
We are using INT environment where the application is deployed at first and then SIT environment, where is the app passed if it is fine on INT. So, testers do all system tests on SIT.
But according to all definitons, SIT is system integration testing which is done after the system tests and validates cooperation of more systems.
So why SIT serves actually for system testing, yet it is said to be a phase which actually follows the system testing?
EDIT: According to common knowledge-books:

Unit

Integration (modules to larger pieces)

System test

().. System Integration Test --if there are more system to integrate

Our apps consist of db, services, frontend. So to make a system test, they must be integrated, otherwise testers cannot do anything. So SIT precedes actual system testing (both funtional and non functional) which does not match with described processes. And environment for testers is also called SIT..

答:
Probably because in terms of environment design, there may not be a difference.

At my previous employer, we had 4 types of environments:

Local (for dev)

Integration/Verification

Performance

Production

IV environments could be used for either integration testing, verification, or both.  They were sometimes used for UAT as well.  The only difference is really in what testers use them for.

Performance was called out as a different type because its characteristics were different.  It had beefier hardware, more servers, etc.  Using it for functional verification would be a waste of money and would cause a process bottleneck (we could have many more IV environments than performance environments).

So the moral of the story is that environment names don't have to perfectly mimic the phases they are a part of, but rather, what type of work they can and cannot be used for.

Ask yourself this question, if you have a dedicated Verification environment and then a SIT environment, what is the value in promoting to SIT once verification is complete?  If SIT can be performed in the same environment as verification once verification is complete, then you can just stick with the single environment or environment category.

If, however, you need a separate environment for SIT either for budget reasons (SIT may by definition require more external components), or for efficiency reasons (QA may have a standard endgame/prelaunch/staging test suite with data setup pre-defined), then you may want to make a dedicated verification and SIT environment.

Sources (wikipedia, of course):

http://en.wikipedia.org/wiki/System_integration_testing

http://en.wikipedia.org/wiki/Integration_testing


问:
Closest Point of Approach (CPA) mathematical formula in ship radar
I was recently searching for the mathematical formula to find closest point of approach (CPA) between one ship and another ship.  I need to apply the formula in my radar ship program and I can't find the correct way to calculates it.

Does anybody know what the correct formula (or pseudo-code) is instead of plotting it manually?

答:
Excuse any math errors that might appear below but the basic approach is valid.

You can represent your ships coordinates using parametric equations.

Pxy(t) = (x(t),y(t))

Meaning that the ship's x-location is represented as a function of time and independently it's y-location is represented as a function of time.

For example,

Xa(t) = t; Ya(t) = 2t + 5 would represent a straight line with coordinates (0, 5) at t = 0.

Xb(t) = t - 4; Yb(t) = t + 10 would represent a straight line with coordinates (-4, 10) at t = 0.

You then plug in both ships parametric equations into the distance formula to calculate the distance from each other at time = t.

D = sqrt((Xa(t) - Xb(t))2 + ((Ya(t) - Yb(t))2)

Using the above examples

D = sqrt((t - (t -4))2 + ((2t + 5) - (t + 10))2)

D = sqrt(16 + t2 -10t + 25) = sqrt(t2 - 10t + 41)

Then solve the equation for its minimum  (t = 5)

Plug in the value for t in the distance formula and you've got the minimum distance and the time between the 2 ships.

The cool thing about this method is that your ships don't have to travel in straight lines (like the example above), as long as their positions can be represented by a function. Of course, the more complex the path the more difficult it is to solve the minimum.

Also, this approach translates to any number of dimensions you want to work in, not just 2-D.

Additionally, it shows one of many uses for that calculus class that everybody thinks was useless for computer science.

If you limit the ships movements to straight lines then this should be relatively straight forward to implement and will run quite quickly. I don't think there's a quicker and more accurate way to do this.

Another good thing using this method is that it is deterministic in how long it will take to execute. The other suggestions of increment the time and see what you get could take a very large number of increments to result in an answer. You won't know how long it takes until you execute it for each situation.


问:
I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett,  Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle".

I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here.

As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags.

I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!

答:
I've done something like this before using a generator (in C#, an infinite loop that yields each loop iteration). Each iteration looks at its pool of songs (or whatever) and tosses out ones that have been played too recently (or whatever negative criteria). Then you pick one from the filtered list, and update your state. As your state drifts (you play non-Sinatra songs) the criteria breaks down and your excluded songs start being re-included.

Of course there's corner cases to deal with:

What happens if you throw out all the songs? (usually just pick one at random, hoping to destabilize the state)

Should some criteria be preferred? (usually the case, maybe you don't want to play Fly Me to the Moon back to back, and would prefer not to play Sinatra back to back, but if that's all you have...)

What happens if your collection of songs gets updated mid-fight? (usually easy to deal with, but concurrency might have issues depending on usage)


答:
I've had good experiences using a IsVisible flag. A bit like this (consider the following to be pseudocode):

```<code>public class CustomLookup
{
    public int ID { get; set; }
    public string Title { get; set; } // drop down text
    public string Description { get; set; } // hover text
    public bool IsVisible { get; set; }

    // this method is likely a repository method, but here for convenience
    public static IEnumerable<CustomLookup> LookupValues()
    {
        return repo.CustomLookups.Where(lookup => lookup.IsVisible);
    }
}
</code>```

Some notes:

It's really simple and easy to maintain in my experience.

When making a lookup item invisible, there needs to be business rules to determine what happens to items that are flagged with that lookup item. Do you force them all into a new/existing one? Do nothing? That's a bit up to your business and the specific information that the lookup represents.

This permits the ability to keep historical information without much worry or fuss for reporting and whatnot, while still permitting the user to do what you describe.

Title: Deleting Lookup Item

Body:
I was wonder what people do in this situation.

You have an admin area of a system where you let users define a list of values they want to see in a dropdowns across the system.

What do you do in your application is a user wants to delete this option?

What do you do with data records which already use this value?

Body:
I've had good experiences using a IsVisible flag. A bit like this (consider the following to be pseudocode):

public class CustomLookup
{
    public int ID { get; set; }
    public string Title { get; set; } // drop down text
    public string Description { get; set; } // hover text
    public bool IsVisible { get; set; }

    // this method is likely a repository method, but here for convenience
    public static IEnumerable<CustomLookup> LookupValues()
    {
        return repo.CustomLookups.Where(lookup => lookup.IsVisible);
    }
}

Some notes:

It's really simple and easy to maintain in my experience.

When making a lookup item invisible, there needs to be business rules to determine what happens to items that are flagged with that lookup item. Do you force them all into a new/existing one? Do nothing? That's a bit up to your business and the specific information that the lookup represents.

This permits the ability to keep historical information without much worry or fuss for reporting and whatnot, while still permitting the user to do what you describe.


答:
Ignoring the outliers of your question that Telastyn brings up, it sounds like you have a variation on the knapsack problem.  Fortunately, it's a pretty well documented algorithm.

From Wikipedia

Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

There are some potentially relevant variations listed in that article along with an additional list of knapsack problems

One variation of the knapsack problem is the multi-objective knapsack problem.  The ant colony algorithm is suggested as a means of solving that problem.  The ant colony approach might be the easiest way for you to avoid the NP-hard aspects of your question.

I could also see considering your problem as an extreme variant of the traveling salesman problem.  Each city to visit is really a song that you want played, but I'm not sure how you would specify the intervals between artists.  This suggestion is also related to / can be solved by the ant colony approach.

Title: I'd like to write an "ultimate shuffle" algorithm to sort my mp3 collection

Body:
I'm looking for pseudocode suggestions for sorting my mp3 files in a way that avoids title and artist repetition. I listen to crooners - Frank Sinatra, Tony Bennett,  Ella Fitzgerald etc. singing old standards. Each artist records many of the same songs - Fly Me To The Moon, The Way You Look Tonight, Stardust etc. My goal is to arrange the songs (or order the playlist) with the maximum space between artists and song titles. So if I have 2000 songs and 20 are by Ella I'd like to hear her only once in every 100 songs. If 10 artists sing Fly Me To The Moon I'd like to hear it once in every 200 songs. Of course I want to combine these two requirements to create my "ultimate shuffle".

I know this is a fairly wide open question. I haven't started programming it yet so I'm just looking for suggestions of a good approach to take. I actually have some other requirements regarding evenly spacing other song attributes but I won't get into that here.

As a starting point I'm modifying code I found here to manipulate mp3 files and read ID3 tags.

I wrote a small app that satisfies my need using parsifal's answer below. I also wrote a follow up question here. Thanks for all the great responses!


答:
Your second example (outer loop from 0 to n, inner loop from 0 to b) would be O(nb), not O(n2). The rule is that you are computing something n times, and for each of those you are computing something else b times, thus the growth of this function depends solely on the growth of n *b.

Your third example is just O(n) -- you can remove all constants as they do not grow with n and growth is what Big-O notation is all about.

As for your last example, yes, your Big-O notation will certainly come from the sort method which will be, if it is comparison-based (as is typically the case), in it's most efficient form, O(n *logn).

Title: Is this a Proper "Rule" for Identifying the "Big O" Notation of an Algorithm?

Body:
I've been learning more about Big O Notation and how to calculate it based on how an algorithm is written. I came across an interesting set of "rules" for calculating an algorithms Big O notation and I wanted to see if I'm on the right track or way off.

Big O Notation: N

```<code>function(n) {
    For(var a = 0; i <= n; i++) { // It's N because it's just a single loop
        // Do stuff
    }
}
</code>```

Big O Notation: N2

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        For(var c = 0; i <= b; c++) { // It's N squared because it's two nested loops
            // Do stuff
        }
    }
}
</code>```

Big O Notation: 2N

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        // Do stuff
    }
    For(var c = 0; i <= b; c++) { // It's 2N the loops are outside each other
        // Do stuff
    }
}
</code>```

Big O Notation: NLogN

```<code>function(n) {
    n.sort(); // The NLogN comes from the sort?
    For(var a = 0; i <= n; i++) {
        // Do stuff
    }
}
</code>```

Are my examples and the subsequent notation correct? Are there additional notations I should be aware of?


答:
I am working under the assumption that this is a "here is my library, run this program and generate an order to play the songs in."

This hasn't been implemented and I am uncertain how well it will preform its shuffling.  It may be that I am a bit too strict in the filter, which would result (I believe) in a prescribed order for the remainder given an initial set of songs.

One has an ideal_gap hash.  This is calculated by the density of a song with a given property (artist, album, title).  If one has 2000 songs and 20 of them are by an artist named Ella, the ideal_gap{'artist'}{"ella"} would be 100.

Having this information one also has the max of the ideal_gap values.  Lets call this max_gap.

Consider: have a maximum to the ideal_gap value to prevent a song that only two artists have sung from preventing the other song from being played 1000 songs later, and also drastically increasing the max_gap value resulting in many iterations of "back off, no songs, back off, no songs".

Examining the last max_gap songs played (this can be populated from a previous run so that if it finished with Frank Sinatra singing Fly Me To the Moon, the next run won't start with the same song by chance), one filters songs out of the library resulting in a set of candidate songs.  A song would only be in the candidate songs if all of its gaps are less than the ideal_gap for those properties.

From the set of candidate songs, select one at random.

Consider:  weighting the set so that songs that attributes with a higher max gap are weighted to be more likely.  This way, one doesn't have all of the larger max gap songs piling up at the end of the playlist.

Consider: instead of having all three properties being greater than the ideal gap, just two out of three.  This may mean that something could be played sooner than the ideal ideal, but increases the size of the candidate song set meaning the "select one at random" has a more options.

If there are no songs that fill the requirements, back off the max_gap by 1, and all ideal_gaps by n/max_gap percent where n is the number of times this has been backed off.  This way if there is a max_gap of 100, and it has been backed off 5 times in this iteration, an ideal_gap of 100 would be adjusted to temporarily be 95, and an ideal_gap of 20 would be adjusted to temporarily be 19.  Repeat backing off the gap until there is at least one candidate song, and then select it as above.

Consider: have a minimum pool size.  This adds to the variance, but may result in having a song played sooner than the ideal gap when there is another song that could be played.


问:
How much business logic should the database implement?
I've worked in some projects where most of the business logic was implemented on the database (mostly through stored procedures). On the other side, I've heard from some fellow programmers that this is a bad practice ("Databases are there to store data. Applications are there to do the rest").

Which of these approaches is the generally better?

The pros of implementing business logic in the DB I can think of are:

Centralization of business logic;

Independency of application type, programming language, OS, etc;

Databases are less prone to technology migration or big refactorings (AFAIK);

No rework on application technology migration (e.g.: .NET to Java, Perl to Python, etc).

The cons:

SQL is less productive and more complex for business logic programming, due to the lack of libraries and language constructs the most application-oriented languages offer;

More difficult (if possible at all) code reuse through libraries;

Less productive IDEs.

Note: The databases I'm talking about are relational, popular databases like SQL Server, Oracle, MySql etc.

Thanks!

答:
There is no one right answer to this. It depends on what you use the database for. In an enterprise application, you need the logic in the database through foreign keys, constraints, triggers, etc. because it is the only place where all possible applications share code.  Further, putting the required logic in code generally means the database is inconsistent and the data is of poor quality. That may seem trivial to an application devloper who is only concerend with how the GUI works, but I assure you that the people trying to use the data in compliance reports find it very annoying and costly when they get billion dollar fines for having data that didn't follow the rules correctly.

In a non-regulatory environment when you don't care as much about the whole set of records and only one or two applications hit the database, maybe you can get away with keeping it all in the application.

ContentLicense: CC BY-SA 4.0


问:
Ring of numbers where adjacent entries sum up to a prime
Given a number n, find a permutation of the numbers 1...n such that all adjacent entries sum up to primes. If such a permutation does not exist, throw an error.

Is there a purely-functional way to do this problem? The solution, which apparently uses backtracking, given uses C++, a language which I am not very familiar with, and loops in loops in loops with very badly-named variable names and a whole lot of mutation. Even if the solution requires mutation, nested loops are really difficult to translate into Racket, the language I currently use.

A more general question would be, how to do backtracking algorithms purely functionally when the concept of backtracking seems to always involve maintaining a state of where you are currently and a big history breadcrumb global state variable that keeps getting mutated?

Of course the dumb way would be to generate all permutations and test them one by one, but are there more efficient ways, preferably implementing a backtracking method, to do so functionally?

Since I use Racket, the solution might not be purely functional but preferably mostly functional, i.e. no repeatedly mutating counter vars in loops or such.

答:
You've got your finger right on the nose of the solution but just don't quite see it, so let's take a quick detour and see if it becomes a little clearer.

In a purely functional language, where you can't mutate anything and therefore cannot have loop indexers etc, how do you write loops?

That's right; you recurse. Why? Because when your only state is in local, and immutable, the only way to change the values in your local is to create new local frames with the values you want.

Now then, back to backtracking, the beauty of not having indices to manage in a loop, is that when you want to move back a few iterations; all you do is return from each frame until you're back where you want to be.

Alternatively, you can backtrack functionally by holding on to your old closures states and move forward into them instead of backwards up the stack when you want to go to an old state. This is however unpleasant as you alluded to above.

Now if you want to get an even more beautiful look at backtracking, you can take a look at Monads and how you do control flow with them, google and I'm sure you can find monadic implementations in racket. Looking at Parser Combinators is a great place to see functional approaches to backtracking.


问:
Service as a Model in MVC
I have a PHP MVC application and a file table. I need to implement the functionality: mark all as read. The best solution for the code I found so far was to put the actual implementation in a Model/Service/FileService.php

The problem is the class FileService will get bloated really fast with different functionality.

What would be a good solution to avoid bloated Services. Should I created different Services for each action?

答:
Start by using your FileService class. Once your service gets to bloated, extract classes from FileService and call these from FileService methods.

So, if you now have FileService->writeFile() with the concrete implementation, your future implementation may contain:

```<code>function writeFile() {
    new FileWriteService()->doStuff();
}
</code>```

So, you can still put all file functions in one class while refactoring and grouping the concrete implementations.

Title: Service as a Model in MVC

Body:
Start by using your FileService class. Once your service gets to bloated, extract classes from FileService and call these from FileService methods.

So, if you now have FileService->writeFile() with the concrete implementation, your future implementation may contain:

function writeFile() {
    new FileWriteService()->doStuff();
}

So, you can still put all file functions in one class while refactoring and grouping the concrete implementations.


问:
What is the difference between "data hiding" and "encapsulation"?
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?

答: Creating a class includes the concept of encapsulation. When you create a class you put data and behaviors inside the class and the class becomes one unit that we call an object. So data hiding is part of encapsulation.</p>


答:
Big oh, by definition means: for a function f(t) there exists a function c*g(t) where c is an arbitrary constant such that f(t) <= c*g(t) for t > n where n is an arbitrary constant, then f(t) exists in O(g(t)).This is a mathematical notation that is used in computer science to analyze algorithms. If your confused I would recommend lookin into closure relationships, that way you can see in a more detailed view how these algorithms get these big-oh values.

Some consequences of this definition: O(n) is actually congruent to O(2n).

Also there are many different types of sorting algorithms. The minimum Big-Oh value for a comparison sort is O(nlogn) however there is plenty of sorts with worse big-oh. For example selection sort has O(n^2). Some non comparison sort may ever have better big-oh values. A bucket sort, for example has O(n).


问:
Permuting a list of numbers by pushing and popping onto a stack
Suppose we have some long stack of numbers. There is another intermediate stack, and a destination stack to be returned in the end. The only two operations allowed is transferring the top of the old stack to the top element of the intermediate stack and transferring the top element of the intermediate stack onto the top of the new stack. List all the possible new stacks that can be produced, assuming the original stack is used up.

I'm using Racket/Scheme. Purely functional solutions are more preferable ;)

Any ideas on how to do it? By some handwaving it seems that the following function correctly predicts whether a certain output sequence is possible, given that the input sequence is sorted from small to big:

```<code>(define (possible? lst)
  (match lst
    [(cons a b)
     (and (if (andmap (λ(x) (< x a)) b) (sorted? b) #t) (possible? b))]
    [x #t]))
</code>```

thus I can simply generate all permuations of the input list and filter out the impossible ones.

It seems that there should be a more elegant solution though, which preferably uses recursion and functional programming instead of nested loops and mutation.

答:
because you have only 2 operations are allowed you can define the sequence of operations as a strict subset of a selection of n from 2n-1 which has (2n-1)!/((n-1)!n!) possibilities (accounting that the first operation is pushing on the intermediate)

this (according to wolfram alpha) doesn't rise as fast as n! (the total amount of permutations)

this tells me that your algorithm cannot create all permutations once n becomes large enough

edit: to generate them all you can find all strings [01]{n} where each at any point there cannot be 1 when there is already an equal amount of 1s and 0s

```<code>rec(i,n,inter,res)
    if i==n
        print res
    rec(i+1,n,inter~i,res)
    if(inter.length>0)
        rec(i,n,inter[0..$-1],rec~inter[$])
</code>```

Body:
because you have only 2 operations are allowed you can define the sequence of operations as a strict subset of a selection of n from 2n-1 which has (2n-1)!/((n-1)!n!) possibilities (accounting that the first operation is pushing on the intermediate)

this (according to wolfram alpha) doesn't rise as fast as n! (the total amount of permutations)

this tells me that your algorithm cannot create all permutations once n becomes large enough

edit: to generate them all you can find all strings [01]{n} where each at any point there cannot be 1 when there is already an equal amount of 1s and 0s

rec(i,n,inter,res)
    if i==n
        print res
    rec(i+1,n,inter~i,res)
    if(inter.length>0)
        rec(i,n,inter[0..$-1],rec~inter[$])


问:
How can I cope with every increasing/changing number of frameworks?
I started coding with php, mysql, html, and javascript back in 2002 and heck that is all you basically needed to create any type of website. Over the years I picked up other languages, but what turned me off were all of the frameworks and JQuery that was popping up every few months and clients (if freelancing) or employers expected you to be an expert on some crap a geek released recently.

Because of this I got out of programming since I don't know if I can constantly throw away all of my previous knowledge and replace it with some new hip fad that does the exact same thing but just uses different function names. I miss knowing the core knowledge of PHP and being able to code from scratch and I'm afraid the skill of mastering a technology to completion is obsolescent.

Is it right to feel this way, and can any of us feel secure about our programming career in the future?

答:
Find the frameworks you like, and stick with them.  Of course, this will require more than a little bit of research and soul-searching, but once you find them, you can proceed to step 2:

If a new framework comes along that appears to do the same thing as your chosen framework, evaluate it, and decide if the additional benefit of the new framework is worth changing your design philosophy and some of the tools in your toolkit.

Is it worth it?

yes: Adopt it

No: Go back to step 1.

Lather, rinse, repeat.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
In Visual Basic 6.0, we had to add error handling blocks to every single method. No exceptions. So we did.

Then we had to explain why parts of the application were slow.


答:
Because of this I got out of programming since I don't know if I can constantly throw away all of my previous knowledge and replace it with some new hip fad that does the exact same thing but just uses different function names.

There's your problem.  Frameworks are not just hip fads that replace function names.  They solve problems in their domains, and it is absolutely your responsibility not to keep up with how to use each individual one, but to know what advances it makes and what problems it solves.

In other words, you should know the strengths and weaknesses of modern frameworks, get decent at some, and be prepared to switch when the amount of time you lose in developing in framework X since it doesn't solve problem P is worth coding in framework Y that does.

Title: How can I cope with every increasing/changing number of frameworks?

Body:
I started coding with php, mysql, html, and javascript back in 2002 and heck that is all you basically needed to create any type of website. Over the years I picked up other languages, but what turned me off were all of the frameworks and JQuery that was popping up every few months and clients (if freelancing) or employers expected you to be an expert on some crap a geek released recently.

Because of this I got out of programming since I don't know if I can constantly throw away all of my previous knowledge and replace it with some new hip fad that does the exact same thing but just uses different function names. I miss knowing the core knowledge of PHP and being able to code from scratch and I'm afraid the skill of mastering a technology to completion is obsolescent.

Is it right to feel this way, and can any of us feel secure about our programming career in the future?


问:
Should my code be DRY or readable if it can't be both?
I'm writing Ruby code for a simple encryption exercise and have frequently run across this dilemma (the exercise is a solitaire cipher if you must know).  It is a question of whether I should pad out my logic with descriptive variables and single step statements that make the function readable instead of a concise, even dense statements that eliminate repetition and/or minimizes opportunities for errors.

My most recent example:  My program takes input, and because of rigid format guidelines, it can easily determine if input should be encrypted or decrypted.  To simplify, once the encryption key and message are converted/generated to be compatible, it's a matter of subtracting the key from the encrypted message or adding the key to an unencrypted message, to get the desired output(think of the key as encryption, message + encryption = code;  code - encryption = message).  The DRY position says to me that I should convert my encrypted message differently from my unencrypted message so that the function which takes encryption key and applies it to the message never needs to distinguish.  I've found that this means I need some nested if statements in the function but the logic appears to be solid.  This code, however, is not easily readable.  This would require some commenting to be clear.

I could, on the other hand, write two different functions that are called based on a flag  that is set when the application determines encryption or decryption.  This would be simpler to read but would duplicate the high level function of applying the encryption key to a message (causing it to be encrypted or decrypted).

Should I lean toward readable code, or concise code?
Or have I missed another way to get this functionality and satisfy both principles?
Is it a position along a scale in which one must consider the purpose of the project and make the best decisions to serve that purpose?

So far, I tend to emphasize concise, DRY code over readable code.

答: I would choose readable (= maintainable) instead of DRY any day of the week. In reality both often align, someone who gets the concept of DRY would generally produce (mostly) readable code.</p>


答:
I'm not sure based on the question that you understand DRY. DRY code is not the same as concise. Quite often it is the opposite.

Here, I'm not sure what the big deal is for this example. Make a function to encrypt, a function to decrypt, helpers for common functionality (mix bytes), and a simple front end to take input and determine encrypt/decrypt... No repeating yourself.

In general though, both DRY and readability exist to help maintaining and extending code. Not all scenarios are equal, a big readability hit to remove a little repeat isn't good, and neither is a bunch of duplication to add a little readability.

If pressed, I would prefer readability. Duplicate code can still be tested - unreadable code leads to you doing (and testing) the wrong thing.

Title: Should my code be DRY or readable if it can't be both?

Body:
I'm writing Ruby code for a simple encryption exercise and have frequently run across this dilemma (the exercise is a solitaire cipher if you must know).  It is a question of whether I should pad out my logic with descriptive variables and single step statements that make the function readable instead of a concise, even dense statements that eliminate repetition and/or minimizes opportunities for errors.

My most recent example:  My program takes input, and because of rigid format guidelines, it can easily determine if input should be encrypted or decrypted.  To simplify, once the encryption key and message are converted/generated to be compatible, it's a matter of subtracting the key from the encrypted message or adding the key to an unencrypted message, to get the desired output(think of the key as encryption, message + encryption = code;  code - encryption = message).  The DRY position says to me that I should convert my encrypted message differently from my unencrypted message so that the function which takes encryption key and applies it to the message never needs to distinguish.  I've found that this means I need some nested if statements in the function but the logic appears to be solid.  This code, however, is not easily readable.  This would require some commenting to be clear.

I could, on the other hand, write two different functions that are called based on a flag  that is set when the application determines encryption or decryption.  This would be simpler to read but would duplicate the high level function of applying the encryption key to a message (causing it to be encrypted or decrypted).

Should I lean toward readable code, or concise code?
Or have I missed another way to get this functionality and satisfy both principles?
Is it a position along a scale in which one must consider the purpose of the project and make the best decisions to serve that purpose?

So far, I tend to emphasize concise, DRY code over readable code.


答:
DRY is a guideline, not a religion.  Those who take it to the point of DRY above all else, have taken it too far.

First and foremost, usable code is paramount.  If the code isn't useful and usable, it isn't... and there isn't any point in writing it in the first place.

Secondly, some day, someone will have to maintain your code.  If your code isn't maintainable, they will break your "beautiful" dense, concise, DRY design while cursing your name.  Don't do this.  I've been that person and every time I see a certain name in the code annotation, I shudder.

Making dense code that lack "descriptive variables" and sticking everything into nested ternary expressions with lambdas without any documentation is clever.  It is nice to know that you can do it - but don't. Clever code is very difficult to debug.  Avoid writing clever code.

Most of the time spent in software is spent in maintenance of the software - not writing it the first time.  Write the code so that you (or someone else) can quickly and easily fix bugs and add features as required to it with as few ideal design breaking changes.


问:
Transforming A Physical Algorithm into a Computerized One
I have realized that its possible to create algorithms that operate physically to solve problems much more efficiently than in a computer itself. Consider the following:

Finding the shortest path between 2 points in a connected graph. If one were to physically create the graph with the edge weights correspond to length of physical connectors and the nodes something corresponding ex: wooden balls and yarn both labeled, then it is possible to generate the graph from data in O(N) time and then determining the shortest path between 2 nodes would simply involve grabbing both those nodes and pulling them so a straight line forms between them (or multiple straight lines!) and the rest hanging. That straight line(s) would be the shortest path for obvious reasons.

How exactly does one take this physical method of solving the problem and implement it in a computer?

答:
I think this is what OP's talking about:

You can almost instantly find the shortest path in real life, but I'm not sure how well this would work with a computer- You could assign a tension value to every node attached to the endpoints, and then to each of the nodes attached to each of those nodes, and so on, but I'm pretty sure other methods would be faster.

Simulating physics for each node would probably take much longer than just finding the distance of each node to the two endpoints.


答: While I'm not certain of exactly what's causing the problem here my experience is that when you find DRY and readability conflicting that says it's time to refactor something out.</p>


答:
There is no such thing as a distinction between a "physical" algorithm and a "computerized" one - the truth of the matter is that an algorithm is a completely conceptual idea or formula.  Computers are capable of doing the exact same subset of calculations that human brains can do, no more and no less - speed is the only real difference.  As such, any formula you have for doing something physically has an equivalent that can be programmed, and visa-versa.  This is the "Computers are Not Magic" principle that all computer science students should come to accept.

I would believe that the typical shortest path algorithm you're familiar with IS functionally equivalent to your rope method, and that you are not taking into account the relative complexity of how choosing the various balls and dropping them would equate to the checks that a computer would perform.

Title: Transforming A Physical Algorithm into a Computerized One

Body:
I have realized that its possible to create algorithms that operate physically to solve problems much more efficiently than in a computer itself. Consider the following:

Finding the shortest path between 2 points in a connected graph. If one were to physically create the graph with the edge weights correspond to length of physical connectors and the nodes something corresponding ex: wooden balls and yarn both labeled, then it is possible to generate the graph from data in O(N) time and then determining the shortest path between 2 nodes would simply involve grabbing both those nodes and pulling them so a straight line forms between them (or multiple straight lines!) and the rest hanging. That straight line(s) would be the shortest path for obvious reasons.

How exactly does one take this physical method of solving the problem and implement it in a computer?


答:
In "physical" algorithm you use massive parallelism of the nature.

Without going to molecular level every node and connector movement is "calculated" in parallel. To get the same speed you would need a computer with too big number of CPU cores and extremely fast communication between them.

So I would say: no, usually direct mapping of physical algorithm to computer does not provide a fast algorithm.


问:
Notify players every x seconds in a multiplayer game
I'm working on a realtime multiplayer game using Django and gevent-socketio, I'm facing some issues:

I need to send an update of the game state to connected players every X seconds (~4 seconds), so basically I need to execute a function every x seconds which does some calculations and sends the connected players the new game state. What is the easiest way to achieve this? is using cron a good choice here or should I look for other tools like celery or ...?

Also, the function needs to operate on some data. querying the database every time the function is executed does not seems to be a good idea, where can I store the game data (which is updated frequently during the game)?

答:
The general language independent idea is to have some kind of a 'Timer' and 'GameStateSender' objects which are connected using an observer pattern. Timer sends events every x seconds and sender listens for these events and sends data upon recieving them. </p>

<p>*Implementation should be discussed on SO</p>

Body:
The general language independent idea is to have some kind of a 'Timer' and 'GameStateSender' objects which are connected using an observer pattern. Timer sends events every x seconds and sender listens for these events and sends data upon recieving them.

*Implementation should be discussed on SO


问:
heuristic for searching through non-perfectly sorted data
Given sorted data, the search solution is obvious.  Given unsorted data, sensible options are sort then search or just linear search.

This question is about what to do if the data is somewhat sorted, but cannot be re-organized (write operations require sector erase, and sectors won't fit in ram).

the details:

Data records are logged sequentially with a timestamp.  The timestamp clock however, from time to time resets to Epoch for a while before it's synced or it's simply adjusted back due to daylight savings etc.

The search result should be the log record with timestamp closest to the time specified.  While performing a binary search for record at a particular timestamp, it is possible to land on a patch of discontiguous log data, and pivot the wrong direction.

Besides a brute linear method, is there a heuristic we can take advantage of here?  e.g. a Simplex Search immune to local minima?

update:

We can assume about 95% of the records are in sorted sequence.  about 5% (scattered through the log) are the dirty hiccups.  The the beginning of the hiccups can be identified when the timestamp goes backwards in time and and have an earlier stamp than the beginning of the log

答:
Additional assumptions

This answer is based on the following additional assumptions:

you can easily determine the timestamp for the beginning of the log, and

it is feasible to store the positions of the hiccups (optional)

Search algorithm

The search is split into two different algorithms really. In case that you search for a log with a timestamp that is after the beginning of the log, you know that it will not be found in the hiccups and use non-hiccup search below. In case that you search for a timestamp before the beginning of the log you use hiccup search instead. If you do not search by the timestamp, but some other criteria, you first try the non-hiccup search due to its 95% coverage and then try the hiccup search if you failed to find anything.

Optionally, you can speed up the non-hiccup search by a preprocessing step.

Preprocessing (optional)

If possible, pre-analyze your data with a linear search to find out the positions of hiccup data. This depends entirely on the feasability of being able to store these ranges, which might be possible given that they only amount to 5% of your logs (or it might not, in which case performance degrades).

Note that the corresponding datastructure should be updated whenever you write new logs, or at least it should be able to tell you up to which point of the logs the preprocessing was performed.

Non-hiccup search

Searching the non-hiccup data is possible via  a combination of binary and linear search. You perform a normal binary search, however, when your pivot element is timestamped before the beginning of the log, i.e. the pivot element is a hiccup, you need to determine the first log entry before the pivot element and use that as the real pivot element of your binary search.

This first log entry with a timestamp after the beginning of the log is found via a linear search starting from the hiccup pivot element. If you know from preprocessing or incremental updates to your cached hiccups where the relevant pivot element is positioned, you can jump there in constant time. If you had to run the full linear search, you update a datastructure to store that these positions are covered by hiccup data, such that next time you can quickly determine the right pivot element.

Hiccup-search

This depends on whether you have made the preprocessing. If not, it is a linear search through all your data (and you can do the preprocessing parts at this time as well). Otherwise, your preprocessed datastructure is able to tell you the positions of the hiccup data and you can search directly through these, i.e. perform a linear search only through the 5% of hiccup data.

Performance

For non-hiccup search with fully preprocessed data you can get almost the performance of a default binary search. Instead of a simple comparison at each step though you need an additional comparison to determine if you hit a hiccup element and if so you need an access to your datastructure to find the real pivot element. This additional work, however, is slightly alleviated by the fact that you not only rule out half your dataset, but you also rule out the hiccup data-part.

Of course, if you have to resort to linear search, this degrades accordingly.

The hiccup search is a bad case if you do not have information about existing hiccups available and need to search linearly through all the data.

Finally, if you do not search for a timestamp, but some other criteria and no such log entry exists, this is your worst-case. In fact, if you have no datastructure for the hiccups, it ends up being slower than linear search, as both search runs may linearly scan the same hiccup positions (though it is still O(n)).

If you do have the datastructure available and fully preprocessed, the worst-case runtime comes down to O(max(log(M)*log(N), M)) where M is the amount of hiccup data, which is searched linearly, and assuming you can lookup the end of hiccup data given any hiccup position from your datastructure in O(log(M)).


答:
I think there are two possible views and issues:

Companies tend to use "system integration testing" / SIT for testing of their application, integrated of more sub-systems. An "INT" environment is usually the first instance that serves as a testing place for developers trying to integrate the app to a working whole. Once they have a stable system on the "INT", it is promoted to "SIT". In this context, it would not mean "integration with external systems rather than integration of sub-systems".

Application could be deployed to "SIT" for system testing and if it passes, on this very same environment it is used for real external system integration. In that case, once the system testing is considered as finished, without any changes to the environment, external systems would be integrated. Also the name "SIT" would reflect what is this environment used for (you do system testing there but eventually it is used for SIT). In this case it is a combination of system testing and system integration, which is not unusual.

Title: Why is SIT called SIT when it serves for system testing?

Body:
I should define a testing strategy and environments and I have encountered rather terminology issue (but might well be my fault) so I hope someone will correct me here.
We are using INT environment where the application is deployed at first and then SIT environment, where is the app passed if it is fine on INT. So, testers do all system tests on SIT.
But according to all definitons, SIT is system integration testing which is done after the system tests and validates cooperation of more systems.
So why SIT serves actually for system testing, yet it is said to be a phase which actually follows the system testing?
EDIT: According to common knowledge-books:

Unit

Integration (modules to larger pieces)

System test

().. System Integration Test --if there are more system to integrate

Our apps consist of db, services, frontend. So to make a system test, they must be integrated, otherwise testers cannot do anything. So SIT precedes actual system testing (both funtional and non functional) which does not match with described processes. And environment for testers is also called SIT..


答:
I am unfamiliar with your specific case, but can give some general guidelines.

The purpose of both readability and DRY is maintainability.

Maintainability is important in most situations you'll spend more time maintaining code than writing it. This is especially true if you consider writing code to be a special kind of maintenance.

Unfortunately, DRY is often misunderstood. This is partly because it seems so simple, but like a lot of simple things it can be, well... complicated.

The intention od DRY is that every unit of functionality exists in just one place. If the principle is followed, the code maintainer who is tasked with changing or verifying that functionality can deal with the code in once. If DRY is not followed then there is a very real danger that some copy of the functionality won't be maintained properly.

The most blatent violation of DRY is copy-paste coding, where entire blocks of code are repeated verbatum in the code base. This is surprisingly common in my experience, and no way that does it add to readability. Therefore, refactoring the code to introduce a common method invariably increases DRY conformance and readability.

The second most blatent violation is "copy-paste and change it a little bit". Again, refactoriing to introduce a comon method with parameters, or breaking a function down into steps and abstracting out the commonalities almost always increases readability.

Then there are the more subtle violations, where functionality is duplicated but the code is different. This always isn't easy to spot, but when you see it and refactor to pull the common code into a single method / class / function then the code is ususally more readable than it was before.

Finally, there are the cases of repetition of design. For example, you might have used the state pattern several times in your code base, and you're considering refactoring to eliminate this repetition. In this case, proceed with caution. You may well be reducing readability by introducing more levels of abstraction. At the same time, you're not really dealing with duplication of functiionality but with duplication of abstraction. Sometimes it is worth it... but often it isn't. Your guiding principle will be to ask, "which of these is more maintainable".

Whenever I make these judgement calls I try to consider the amount of time people will spend maintaining the code. If code is core business functionality then it'll probably need more maintenance. In that cases I aim to make the code maintainable for people who are familiar with the code base and the abstractions involved. I'd be happier to introduce a little more abstraction to reduce repetition. In contrast, a script that is rarely used and infrequently maintained might be less easy to grasp for the maintainers if it involves too much abstraction. In that case I would err on the side of repetition.

I also consider the experience level of other members of my team. I avoid "fancy" abstractions with inexperienced developers, but leverage insustry recognised design patterns with more mature groups.

In concusion, the answer to your question is to do whatever makes your code most maintainable. What that means in your scenario is up to you to decide.


问:
How to end my dependency on .NET?
I have been developing Windows GUI applications since many years and jumped into .NET in early 2005. .NET is a undoubtedly a remarkable platform and I am still using it, but with a variety of technologies out there, I don't want to remain dedicated to this camp. I want to learn new languages with which I can develop GUI applications.

I am learning Ruby and just installed Python. I read about WxRuby, a framework for developing Windows GUI app. in Ruby. I am searching for a similar framework for Python.

Apart from that I want to know which language is more suitable for a production-level GUI app. I doubt that Ruby is more focused on Web platform with it's glamor, Ruby on Rails.

I know that I may not get those rich .NET classes and that impressive Visual Studio IDE, but still I want to follow the road less traveled. I don't want to go with IronPython and IronRuby, however sometime later, I may dip hands to explore them.

答:
Remember that the hard-core non-microsoft non-apple people are command-line driven, and GUI design is fairly useless there. They will, to some extent, compromise and make GUIs in HTML, to be consumed by browsers, but that's for their clients, not for themselves.

If you with to stay in the GUI world, I suppose you might want to look at Apple or stay with .NET on Windows.

Makes sense?

HTH

ContentLicense: CC BY-SA 2.5

Title: How to end my dependency on .NET?


答:
If your functions become more complicated and longer (thus less readable) when you try to make them DRY, then you are doing it wrong. You are trying to put too much functionality in one function because you think that this is the only way of avoiding to repeat the same pieces of code in a second function.

Making code DRY almost always means refactoring common functionality to smaller functions. Each of that function should be simpler (and thus more readable) than the original one. To keep everything in the original function on the same level of abstraction, this may also mean to refactor additional parts out which are not used elsewhere. Your original function then becomes a "high level function", calling the smaller ones, and it gets smaller and simpler, too.

Doing this consequently leads mostly to different levels of abstractions in your code - and some people believe such kind of code is less readable. To my experience, this is a fallacy. The key point here is to give the smaller functions good names, introduce well-named data types and abstractions which can be easily grasped by a second person. That way "DRY" and "readability" should only very, very seldom get in conflict.


问:
Google Blink (new WebKit fork): Meaning of "Moving DOM into Javascript"?
From the Blink Blog:

Finally we’d like to explore even larger ideas like moving the entire Document Object Model (DOM) into JavaScript.

What does this mean? Does it mean WebKit's DOM is currently not coded in JavaScript but in some other language? Does it mean that they want to expose more public accessors to the DOM? Or what?

答:
The way I read it there are two options. But before we look into this, you have to understand how the old model works.

In most, if not all implementations of HTML rendering engines, the DOM is implemented in C or C++ and the JavaScript engine is an add-on that has bindings exported to the DOM. This makes sense, if you look at how HTML and JavaScript evolved. But a lot of time is wasted in marshaling the calls from JavaScript to C/C++ and back.

The first option is that the DOM becomes more closely bound to the JavaScript engine. Basically the DOM objects becomes core JavaScript objects, like Array. This does not do much except reduce some marshaling, since the DOM uses the native data types from the JavaScript engine. The DOM is then still implemented in C or C++.

The second option and probably what they mean, is that the actual DOM is implemented in JavaScript. The downside is that the access to the DOM is fully interpreted, but on the upside it removes any marshaling. This is probably a net gain, since the DOM is mostly data anyway.

Then again I can't give you a definite answer - I don't work for Google and thus don't have that much insight.

OwnerDisplayName: BSalita

OwnerDisplayName: rioki


问:
Why is using named routes for generating outbound URLs a violation of Separation of Concerns?
https://stackoverflow.com/questions/98734/what-is-separation-of-concerns

In computer science, separation of concerns (SoC) is the process of
  breaking a computer program into distinct features that overlap in
  functionality as little as possible. A concern is any piece of
  interest or focus in a program. Typically, concerns are synonymous
  with features or behaviors. Progress towards SoC is traditionally
  achieved through modularity and encapsulation, with the help of
  information hiding.

From Pro Asp.Net MVC 4 book ( page 375 ):

The problem with relying on route names to generate outgoing URLs (
  @Html.RouteLink("Click me", "MyOtherRoute","Index", "Customer") is
  that doing so breaks through the separation of concerns that is so
  central to the MVC design pattern. When generating a link or a URL in
  a view or action method, we want to focus on the action and controller
  that the user will be directed to, not the format of the URL that will
  be used. By bringing knowledge of the different routes into the views
  or controllers, we are creating dependencies that we would prefer to
  avoid.

a) I understand that we create a dependency ( between action method/view and a routing configuration module ) by having Html.RouteLink ( called within action method or view ) specifying the name of the route we want to use.

But is introducing such a dependency already considered a violation of SoC? Namely, even though we created a dependency between the two modules, we haven't actually introduced any additional functionality/concern into either of the modules ( the definition of SoC implies that violation of SoC occurs when new functionality/concern is introduced into a module )

b) Anyhow, I don't understand how will simply generating an URL ( within action method/view ) by specifying a named route bring focus to the format of the URL?

Thank you

答:
It doesn't violate the SOC principle; the author is wrong.

Named routes typically encapsulate the controller and the action as well as
URL, which frees the view from having to know them. Used this way they actually
promote separation of concerns as the view is freed from knowing the name of the
controller and action.

Here is an example:

```<code>routes.MapRoute(name: "SignUpPromotion",
                url: "some/url",
                new { controller = "SignUp", action= "Promotion" });
</code>```

By using Html.RouteLink("SignUpPromotion"), I've freed the view from having to know
the names of the controller and the action. I could rename the action or even move it
to a new controller without affecting the view or changing the URL.

Body:
It doesn't violate the SOC principle; the author is wrong.

Named routes typically encapsulate the controller and the action as well as
URL, which frees the view from having to know them. Used this way they actually
promote separation of concerns as the view is freed from knowing the name of the
controller and action.

Here is an example:

routes.MapRoute(name: "SignUpPromotion",
                url: "some/url",
                new { controller = "SignUp", action= "Promotion" });

By using Html.RouteLink("SignUpPromotion"), I've freed the view from having to know
the names of the controller and the action. I could rename the action or even move it
to a new controller without affecting the view or changing the URL.


答: Well, wxRuby is just a Ruby binding for wxWidgets, an awesome cross-platform GUI toolkit.  There is a similar binding for Python called wxPython, as well as bindings for many other languages.</p>

Title: How to end my dependency on .NET?

Body:
I have been developing Windows GUI applications since many years and jumped into .NET in early 2005. .NET is a undoubtedly a remarkable platform and I am still using it, but with a variety of technologies out there, I don't want to remain dedicated to this camp. I want to learn new languages with which I can develop GUI applications.

I am learning Ruby and just installed Python. I read about WxRuby, a framework for developing Windows GUI app. in Ruby. I am searching for a similar framework for Python.

Apart from that I want to know which language is more suitable for a production-level GUI app. I doubt that Ruby is more focused on Web platform with it's glamor, Ruby on Rails.

I know that I may not get those rich .NET classes and that impressive Visual Studio IDE, but still I want to follow the road less traveled. I don't want to go with IronPython and IronRuby, however sometime later, I may dip hands to explore them.


问:
Vagrant's Users: What are its drawbacks?
I've been studying http://www.vagrantup.com/ for several days and I'd like a feedback by people using it in a professional context or for personal projects. I think I get what positive things can bring Vagrant but I have questions about its drawbacks:

I'm a php developer and I work in a small company. I'm wondering if Vagrant could be useful for me and newcomers in my company since it's forcing a total development environment. I mean, people often prefers to work on their OS (Linux/Mac/Windows). How do you deal with that, do you force everyone to use Linux for example?

Doesn't it add complexity since you are entirely working on a Virtual Machine?

Don't you fear your VM main file get corrupted one day and you wouldn't be able to use it again? I feel nervous about using VM because of that.

Thank you.

答:
The main advantage of working with a virtual machine is that you can quickly get a development environment up and running. A modern, complex application probably uses a number of external dependencies, like various database servers, message queue daemons and whatnot. Installing these on every developer's machine individually for a local development environment can be quite a hassle. Using a virtual machine image, you can distribute a pre-configured environment easily.

This does not mean that you set this image up once and cross your fingers that it'll never corrupt. It also doesn't mean that developers are writing their code inside the virtual machine. To create the virtual machine, you should create scripts which can set up a base OS to the desired state. Look at Ansible, Chef, Puppet, simple shell scripts and similar tools for that. These scripts can be used to set up a virtual machine, your production system, test systems etc all from the same source. Creating and distributing a complete image of a virtual machine is just a time saver, since such scripts could take a while to run. It also allows you to easily reset your environment to a known good state if you have messed things up. The VM image is not your one and only source though; if it corrupts it doesn't matter, since it doesn't hold any data or code and since you can simply recreate it.

Secondly, vagrant maps paths inside the virtual machine to paths on the host machine. Your developers can simply write their code as usual on their regular machine and just execute it inside the VM. Since the paths are shared this can happen immediately without needing to copy any files back and forth.

So:

Maybe vagrant can be useful to you, if your app requires a complex setup.

Not really, since nothing much changes.

See above.


问:
Design for multiple type return
I am working in C++ and I have this problem.

```<code>class Container {
   Container(int which_type_to_use_a_b_or_c);

   A & getData(A & prototype);
   B & getData(B & prototype);
   C & getData(C & prototype);

private:
   A a;
   B b;
   C c;
   int type_used;

}
</code>```

Only one of the A,B or C datatypes is actually used in a class Container instantiation. The constructor flag decides which one to use. When it's time to get a reference to the internal object, I need a getData routine which returns the reference of the different type. In order to disambiguate, I pass a "prototype" A() B() or C().

I don't really like this pattern, but I am unable to find anything better due to my limited palette in c++. Do you have any other approach available? please note that templating Container over A, B or C is not an option due to other constraints.

答:
It looks a lot like Boost.Variant which might either replace your class or help implementing it easily.

Basically it provide a way to allocate memory that can contain either A, B, C which are defined at compile-time. When you need to get the data, it's easy to retrieve what you want.
You can check dynamically which time is stored, and if the user code already know which type should be available, it can just extract the value and get an exception if it's not the expected type.

Title: Design for multiple type return


答:
You could use a discriminated union, like Boost.Variant

```<code>class Container {
    typedef boost::variant<A,B,C> ABC;
    enum Type { UseA, UseB, UseC };

    explicit Container(Type t);

    ABC & getData();

private:
    ABC value;
}
</code>```

but frankly this feels like an X-Y problem. What are you actually trying to accomplish?

NB. you said in a comment

... we also can't use pointers, only references

you may be interested to know that runtime polymorphism works just fine with references (even if it doesn't help here).

Title: Design for multiple type return

Body:
I am working in C++ and I have this problem.

```<code>class Container {
   Container(int which_type_to_use_a_b_or_c);

   A & getData(A & prototype);
   B & getData(B & prototype);
   C & getData(C & prototype);

private:
   A a;
   B b;
   C c;
   int type_used;

}
</code>```

Only one of the A,B or C datatypes is actually used in a class Container instantiation. The constructor flag decides which one to use. When it's time to get a reference to the internal object, I need a getData routine which returns the reference of the different type. In order to disambiguate, I pass a "prototype" A() B() or C().

I don't really like this pattern, but I am unable to find anything better due to my limited palette in c++. Do you have any other approach available? please note that templating Container over A, B or C is not an option due to other constraints.

Body:
You could use a discriminated union, like Boost.Variant

class Container {
    typedef boost::variant<A,B,C> ABC;
    enum Type { UseA, UseB, UseC };

    explicit Container(Type t);

    ABC & getData();

private:
    ABC value;
}

but frankly this feels like an X-Y problem. What are you actually trying to accomplish?

NB. you said in a comment

... we also can't use pointers, only references

you may be interested to know that runtime polymorphism works just fine with references (even if it doesn't help here).


答:
in addition to the concept of Boost::Variant or simple unions, this is a problem that may be better solved using a template. (and I know you don't want to use templates, but if you won't tell us why, I'm going to answer anyway - it might help someone else new to C++ get the right answer)

So you'd create a class where the type you're containing is not passed in as a flag, but is passed as a 'compiler instruction' to generate a class specifically for the type you want to use.

eg.

```<code>template <class T>
class Container{
    T the_type_thats_used;
  public:
    T & getData(T & prototype);
    typedef T type_used;
};
</code>```

this is what templates are used for, a good example is the STL that has a load of container classes that work this way.

Title: Design for multiple type return

Body:
in addition to the concept of Boost::Variant or simple unions, this is a problem that may be better solved using a template. (and I know you don't want to use templates, but if you won't tell us why, I'm going to answer anyway - it might help someone else new to C++ get the right answer)

So you'd create a class where the type you're containing is not passed in as a flag, but is passed as a 'compiler instruction' to generate a class specifically for the type you want to use.

eg.

template <class T>
class Container{
    T the_type_thats_used;
  public:
    T & getData(T & prototype);
    typedef T type_used;
};

this is what templates are used for, a good example is the STL that has a load of container classes that work this way.


答:
Lets analyse the physical solution in more detail.

First construction of the graph is going to be O(E+V) as you have to tie each edge to each connected node (E is number of edges, V number of vertices on a well connected graph this will be O(E)). In terms of complexity this will be the same as constructing a graph is software, but we can already imagine that the constant factors will be much larger for string tying.

Second pulling the start and end nodes does not give you the answer instantaneously, the force must propagate along the shortest path, so we can select the answer in O(L) where L is the length of the shortest path, this still looks quite good though, and that is because the force propagates in parallel. However we still have other problems here, if there are two paths that are very similar length then it will be hard to choose between them as the finite width of your strings and knots will mean they are both under tension.

Lastly lets look at scale. All your strings have a physical mass, and maximum tensile strength. Assuming we have steel wire we have a breaking length of 25.9 km. In the worst case your shortest path is 3 nodes with all other edges/nodes hanging off the middle node so this will mean (in steel) the maximum length of all the wire in your graph will be about 25.9 km. given the high constant factor in construction this may mean there are very few or even no graphs for which it is both possible and quicker to solve the shortest path problem physically.

Converting to a computer solution, if we network V hardware nodes with E message channels such that the time to propagate a message along a channel is the weight of an edge, I think we can again see that if we can send message in parallel along all edges we can find the shortest path in O(L) time. And this I think demonstrates the key issue, you are using O(E+V) hardware to do this, if we convert this to software on O(1) hardware in the straight forward way then the algorithm becomes O(L+E+V) as we now have to simulate all our hardware in series. We can now see this is worse than the usual algorithms.


问:
How to get a Web Application to communicate between users
I am developing a multipalyer web Application for Anti-Chess. It would be hosted on Google App Engine.

I have a few questions:

How do I get two different users who have opened the webapp on their browser to communicate moves with each other. P2P or through the server. If through the server, can I store some moves on it (specifically talking about GAE), to test bots later?

How to implement this P2P/Server connection. As a developer I know jack about Networking. But I hav heard of things like Socket programming, HTTP request etc, what can/should I use. And where can I read up on that!

If I don't go for GAE, would it cost me too much to get some server space and hosting capabilities? And people tell me that then deploying the application is tougher than on GAE. Is that so. Where can I read up on deploying the web Application on Servers.

Where does the code for networking go? I will be using Django with python as the web framework, front-end would be HTML, CSS, and JavaScript. Should I make a separate module for the networking methods and then introduce a method calls wherever needed in the game play?

Someone suggested me on using Unity software for developing. Is it good, Does it make it simple to do work? Will it cover all the parts of the development, the front end and the back end and the deployment?

Note: I am a first timer in web Application, I have coded games before, but always without GUI. And also with no multiplayer over the network capabilities!

答:
As it's a web application, you can't communicate directly between clients, you must involve the server (in fact, to prevent cheating through hacked clients, I'd never implement anything like this as a p2p system, unless no state is ever sent to the server at all).

A REST or JSON call is probably easiest to achieve, each client sending its state to the server at regular intervals and getting validation and updated state of other clients in reply.


问:
Spring - Confusion over configuration?
Somewhere I read Spring offers convenience over configuration. But Spring folks are bringing in so much changes over the configuration , that I am now really getting confused to use the xml configuration or the annotation.

I would like anyone to suggest a surefire methodology or rule of thumb in using xml and annotations.

Examples at SO to show that many beginners like me are getting confused over the configuration.

link-1

I don't seem to grasp the functionality behind <context:annotation-config> and <context:component-scan>.

From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.

To confuse me even more, there is an annotation-config attribute on <context:component-scan>...

link 2

I still have  the component scan tag:

```<code><context:component-scan base-package="com.mycompany.maventestwebapp" />
</code>```

but I have also another tag (that look like have similar task), this one:

```<code><annotation-driven />
</code>```

What is the difference between these two tags?
  An other "strange" thing is that the previous example (that don't use the annotation-driven tag) is very similar to the project create by STS using the Spring MVC Template project but if I delete the annotation-driven tag from its configuration file the project don't run and give me the following error: HTTP Status 404 -...

Spring 3.2 no longer need cglib for proxying , but lower versions uses cglib. A quote from the springsource blog

In order to generate such proxies, Spring uses a third party library
  called cglib. Unfortunately, this project is not active anymore. In
  Spring 3.2, it is very likely that Spring will be using Javassist
  instead by default.

Are these enough to suggest that Spring is Confusion over configuration ?

答:
Spring aims to provide you a framework where there is "convention over configuration".  However the reality is that Spring applications do need a certain amount of configuration.

In the Spring 2.5.x and earlier versions, the common idiom was to provide this configuration via XML. With Spring 3.0+, the idiomatic way is to use annotations (something that Java EE6/7 also encourage).

As a side note, it can be amusing (saddening?) to see an annotated JPA entity, it's rather easy to add 4+ annotations to a single field....

Title: Spring - Confusion over configuration?


问:
What is the difference in a developer's years of experience with a language?
As stated by the title, what is the difference in years of experience in given language in terms of developers? For example, if one developer has had five years working with language A and the other developer has had two years working with language B followed by three years working with language A, would there be perceivable difference between them?</p>

答:
And you're using them for language A, I assume?  (Clearly, there would be a difference in language B.)

It partly depends on the differences between A and B (particularly if we shorten the second developer's experience with A).  If they're fairly similar, there will be essentially no difference in experience.  If A has considerably different concepts,  three years is still likely enough to learn them.  Given a very large library and complicated tools, there may be a difference between three and five years.

Of course, what matters most here is the individual.  A good developer can learn a new platform thoroughly in three years, and so this shouldn't be an issue.


答:
What you're describing is an analog computer. These used to be actually built for certain purposes and old CS books had chapters devoted to them. These chapters got shorter over time and eventually disappeared, as did the machines. The problem is that analog computers

don't scale well

are very limited in the precision of results they can give

are very inflexible (they have to be built for a specific, relatively narrow purpose)

As for "Transforming A Physical Algorithm into a Computerized One" - that's not possible, because the core of the analog computer is not an algorithm at all - it's just using the laws of physics operating continuously on a mechanism, while an algorithm consists of discrete steps.

There's a reason that physical simulations are some of the most demanding applications for supercomputers, for which you can essentially never have enough computing power.


问:
Open source licenses (specifically GPL) & gamemaker's source format
Now with gamemaker studio source files are no longer stored in a proprietary format - instead they are stored as simple XML files containing all data. Now I am wondering, can projects created with gamemaker be licensed using an open source license - especially wondering about the GPL and BSD/APACHE families?

And if so how to? The biggest objection I see is that all files are generated by gamemaker - and regenarated each time gamemaker saves/loads. The main problem with this is that GM will remove any "unrecognized" data from the xml (so any comments). Including copyright notices.

A second problem is that gamemaker typically creates a few dozen files, basically for each function a separate file is created.

A typical generated xml looks as following:

```<code><!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->
<object>
  <spriteName><undefined></spriteName>
  <solid>0</solid>
  <visible>-1</visible>
  <depth>0</depth>
  <persistent>0</persistent>
  <parentName><undefined></parentName>
  <maskName><undefined></maskName>
  <events>
    <event eventtype="0" enumb="0">
      <action>
        <libid>1</libid>
        <id>603</id>
        <kind>7</kind>
        <userelative>0</userelative>
        <isquestion>0</isquestion>
        <useapplyto>-1</useapplyto>
        <exetype>2</exetype>
        <functionname></functionname>
        <codestring></codestring>
        <whoName>self</whoName>
        <relative>0</relative>
        <isnot>0</isnot>
        <arguments>
          <argument>
            <kind>1</kind>
            <string>xml = FS_xml_open("C:\Users\user\Documents\filesystem\student.xml");

</string>
          </argument>
        </arguments>
      </action>
    </event>
    <event eventtype="9" enumb="13">
      <action>
        <libid>1</libid>
        <id>603</id>
        <kind>7</kind>
        <userelative>0</userelative>
        <isquestion>0</isquestion>
        <useapplyto>-1</useapplyto>
        <exetype>2</exetype>
        <functionname></functionname>
        <codestring></codestring>
        <whoName>self</whoName>
        <relative>0</relative>
        <isnot>0</isnot>
        <arguments>
          <argument>
            <kind>1</kind>
            <string>var root_elem = FS_xml_root_element(xml);
show_message("start with root element: " + FS_xml_get_elem_name(xml, root_elem));
xml_test_display_func(xml, root_elem, "");
</string>
          </argument>
        </arguments>
      </action>
    </event>
  </events>
  <PhysicsObject>0</PhysicsObject>
  <PhysicsObjectSensor>0</PhysicsObjectSensor>
  <PhysicsObjectShape>0</PhysicsObjectShape>
  <PhysicsObjectDensity>0.5</PhysicsObjectDensity>
  <PhysicsObjectRestitution>0.100000001490116</PhysicsObjectRestitution>
  <PhysicsObjectGroup>0</PhysicsObjectGroup>
  <PhysicsObjectLinearDamping>0.100000001490116</PhysicsObjectLinearDamping>
  <PhysicsObjectAngularDamping>0.100000001490116</PhysicsObjectAngularDamping>
  <PhysicsObjectFriction>0.200000002980232</PhysicsObjectFriction>
  <PhysicsObjectAwake>-1</PhysicsObjectAwake>
  <PhysicsObjectKinematic>0</PhysicsObjectKinematic>
  <PhysicsShapePoints/>
</object>
</code>```

(where you can see that the amount of non-generated actual code programmed corresponds to 4 lines). Adding something like

答:
IANAL, but I think Earlz's comment is spot on (of course different countries might have different rules, contact an intellectual property lawyer if you want to be 100% certain).

Copyright is implicit, it belongs to the original creator. That's the person who pressed the "generate" button in a computer program as much as it is the photographer who presses the shutter release on his camera (which would also fall under Michael's "generated and therefore can't be copyrighted", when we all know photos ARE copyrighted material) or the painter putting his pencils to the canvas.

Of course copyright and licensing are different beasts, but generally speaking the copyright owner can determine how to license his or her creations, barring restrictions placed upon him by the law or other contracts (I don't know Gamemaker, but have seen in the past code generators that required generated code to be released under a specific license, so double check).

There's no need to have a license statement in each code file, just as there's no need to have a copyright notice in each work (source file, photo, painting). As long as you notify the recipient of the terms under which he can use your work, that should be enough (Da Vinci didn't write a license agreement on the back of the Mona Lisa either, nor Ansel Adams on his photographs...).


问:
How to close a bug that is no longer relevant
I'm currently on a medium-sized team of web developers. We're using jira for bug tracking.

We're working on a product with frequent layout changes. A lot of times bugs are filed about a bug in the layout in some browser. Sometimes, by the time we get around to dealing with a low priority bug, the layout has already changed and it is no longer relevant.

What should we close it as?

What I mean is how we should treat these issues? While Jira is the bug tracking software we use, I'm more interested in how to handle these sort of issues in general.

Does it even matter? (We might return to the layout later, but it's very unlikely)

答: We resolve such issues as 'Obsolete'. This is not a default resolution option in JIRA but it is easy enough to add.</p>


答:
JIRA (and I'm sure other bug trackers) allows you to specify custom resolutions so you should be able to set up a "Overtaken By Events" or "Irrelavant" resolution, or similar to allow you to express the closure how you want

Does it matter? that depends, for us I'd say yes as our customer is overly concerned about the number of open issues in our tracker, so for us its useful to be able to say these are closed because they are no longer relevant without deleting the issue entirely.

Even without a customer concerned by issue numbers, pruning old open issues that are no longer relevant is definitely useful just to reduce clutter in the browser.

Title: How to close a bug that is no longer relevant

Body:
I'm currently on a medium-sized team of web developers. We're using jira for bug tracking.

We're working on a product with frequent layout changes. A lot of times bugs are filed about a bug in the layout in some browser. Sometimes, by the time we get around to dealing with a low priority bug, the layout has already changed and it is no longer relevant.

What should we close it as?

What I mean is how we should treat these issues? While Jira is the bug tracking software we use, I'm more interested in how to handle these sort of issues in general.

Does it even matter? (We might return to the layout later, but it's very unlikely)