答:
Importing the module doesn't waste anything; the module is always fully imported (into the sys.modules mapping), so whether you use import sys or from sys import argv makes no odds.

The only difference between the two statements is what name is bound; import sys binds the name sys to the module (so sys -> sys.modules['sys']), while from sys import argv binds a different name, argv, pointing straight at the attribute contained inside of the module (so argv -> sys.modules['sys'].argv). The rest of the sys module is still there, whether you use anything else from the module or not.

There is also no performance difference between the two approaches. Yes, sys.argv has to look up two things; it has to look up sys in your global namespace (finds the module), then look up the attribute argv. And yes, by using from sys import argv you can skip the attribute lookup, since you already have a direct reference to the attribute. But the import statement still has to do that work, it looks up the same attribute when importing, and you'll only ever need to use argv once. If you had to use argv thousands of times in a loop, it could perhaps make a difference, but in this specific case it really does not.

Hence, the choice between one or the other should be based solely on coding style.

In a large module, I'd certainly use import sys; code documentation matters, and using sys.argv somewhere in a large module makes it much clearer what you are referring to than just argv ever would.

If the only place you use argv is in a '__main__' block to call a main() function, by all means use from sys import argv if you feel happier about that:

```<code>if __name__ == '__main__':
    from sys import argv
    main(argv)
</code>```

I'd still use import sys there myself. All things being equal (and they are, exactly, in terms of performance and number of characters used to write it), that is just easier on the eye for me.

If you are importing something else altogether, then perhaps performance comes into play. But only if you use a specific name in a module many times over, in a critical loop for example. But then creating a local name (within a function) is going to be faster still:

```<code> import somemodule

 def somefunction():
      localname = somemodule.somefunctionorother
      while test:
          # huge, critical loop
          foo = localname(bar)
</code>```

Title: 'import module' vs. 'from module import function'

Body:
I have always been using this method:

```<code>from sys import argv
</code>```

and use argv with just argv. But there is a convention of using this:

```<code>import sys
</code>```

and using the argv by sys.argv

The second method makes the code self documented and I (really) adhere to it. But the reason I prefer first method is it is fast because we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them). Note that I need just argv and all other functions from sys are useless to me.

So my questions are. Does the first method really makes the script fast? Which method is preferred most? Why?

Body:
Importing the module doesn't waste anything; the module is always fully imported (into the sys.modules mapping), so whether you use import sys or from sys import argv makes no odds.

The only difference between the two statements is what name is bound; import sys binds the name sys to the module (so sys -> sys.modules['sys']), while from sys import argv binds a different name, argv, pointing straight at the attribute contained inside of the module (so argv -> sys.modules['sys'].argv). The rest of the sys module is still there, whether you use anything else from the module or not.

There is also no performance difference between the two approaches. Yes, sys.argv has to look up two things; it has to look up sys in your global namespace (finds the module), then look up the attribute argv. And yes, by using from sys import argv you can skip the attribute lookup, since you already have a direct reference to the attribute. But the import statement still has to do that work, it looks up the same attribute when importing, and you'll only ever need to use argv once. If you had to use argv thousands of times in a loop, it could perhaps make a difference, but in this specific case it really does not.

Hence, the choice between one or the other should be based solely on coding style.

In a large module, I'd certainly use import sys; code documentation matters, and using sys.argv somewhere in a large module makes it much clearer what you are referring to than just argv ever would.

If the only place you use argv is in a '__main__' block to call a main() function, by all means use from sys import argv if you feel happier about that:

if __name__ == '__main__':
    from sys import argv
    main(argv)

I'd still use import sys there myself. All things being equal (and they are, exactly, in terms of performance and number of characters used to write it), that is just easier on the eye for me.

If you are importing something else altogether, then perhaps performance comes into play. But only if you use a specific name in a module many times over, in a critical loop for example. But then creating a local name (within a function) is going to be faster still:

 import somemodule

 def somefunction():
      localname = somemodule.somefunctionorother
      while test:
          # huge, critical loop
          foo = localname(bar)


问:
When to apply corrections on data gathered from a server
I have an program that collects data from other servers. I don’t have access to these servers so I can’t change anything. The servers can give incorrect data, I can solve the problem but I’m a little bit stuck on “when to do the correction”.

I download the data from the server, the data gets processed and stored on the hard-drive. When the same data is needed an there is no change, then I use the old data. So this is basically caching.

There are 2 places where I could apply the correction.

When I receive the data from the other servers;

After I cache the data. So right before I use it.

When I apply the correction on the downloaded data directly, then the server doesn’t need to do much calculations. It’s only corrected once.

When I apply the correction after I took it from the cache or when isn’t cached after I cache the data. Then I need more CPU power. But this gives me the advantage to access the original data at all time. I could fall back when I made a mistake and apply a correct correction.

So the question is, when should I apply the correction? And why should I do it that way.

答:
This is going to be a question of performance and dependent on your expected application usage. If your application is going to be downloading the data infrequently but distributing it to users frequently I would do my calculations when writing the data to disk. If you are going to be downloading a lot of data sets from the servers which may never be accessed by a user I would move the processing to when you are getting the data from disk / from a cache.

Quick note here:

When I apply the correction after I took it from the cache or when isn’t cached after I cache the data. Then I need more CPU power. But this gives me the advantage to access the original data at all time. I could fall back when I made a mistake and apply a correct correction.

There is nothing that says that you couldn't keep both a raw copy of the data as well as a modified one while applying the correction at the time of downloading the data.

ContentLicense: CC BY-SA 3.0


问:
'import module' vs. 'from module import function'
I have always been using this method:

```<code>from sys import argv
</code>```

and use argv with just argv. But there is a convention of using this:

```<code>import sys
</code>```

and using the argv by sys.argv

The second method makes the code self documented and I (really) adhere to it. But the reason I prefer first method is it is fast because we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them). Note that I need just argv and all other functions from sys are useless to me.

So my questions are. Does the first method really makes the script fast? Which method is preferred most? Why?

答:
I use from imports whenever it improves readability. For example, I prefer (semicolons are only to save space here):

```<code>from collections import defaultdict
from foomodule import FooBar, FooBaz
from twisted.internet.protocol import Factory
defaultdict(); FooBar(); FooBaz(); Factory()
</code>```

instead of:

```<code>import collections
import foomodule
import twisted.internet.protocol
collections.defaultdict(); foomodule.FooBar(); foomodule.FooBaz()
twisted.internet.protocol.Factory()
</code>```

The latter is harder to read (and write) for me because it contains so much redundant information. Also, it's useful to know ahead of time what parts of a module I'm using.

I prefer regular imports if I'm using lots of short names from a module:

```<code>import sys
sys.argv; sys.stderr; sys.exit()
</code>```

Or if a name is so generic that it doesn't make sense outside of its namespace:

```<code>import json
json.loads(foo)

from json import loads
loads(foo)  # potentially confusing
</code>```

Body:
I use from imports whenever it improves readability. For example, I prefer (semicolons are only to save space here):

from collections import defaultdict
from foomodule import FooBar, FooBaz
from twisted.internet.protocol import Factory
defaultdict(); FooBar(); FooBaz(); Factory()

instead of:

import collections
import foomodule
import twisted.internet.protocol
collections.defaultdict(); foomodule.FooBar(); foomodule.FooBaz()
twisted.internet.protocol.Factory()

The latter is harder to read (and write) for me because it contains so much redundant information. Also, it's useful to know ahead of time what parts of a module I'm using.

I prefer regular imports if I'm using lots of short names from a module:

import sys
sys.argv; sys.stderr; sys.exit()

Or if a name is so generic that it doesn't make sense outside of its namespace:

import json
json.loads(foo)

from json import loads
loads(foo)  # potentially confusing


问:
Can profiling be used to verify if optimization was successful?
I know that profiling is useful to identify bottlenecks and determining what parts of the code require how much time to execute. The latter isn't always very easy to track in the midst of other paths being executed, so once I decide what I want to optimize it might be problematic to see the improvement in numbers. This is especially true in desktop apps which run constantly and it is difficult to: execute the same path and execute it the same number of times to have reliable comparison.

It won't help me if before optimization the function ran X times and took 500 milliseconds, and after optimization it run Y times and took 400 milliseconds.

In such cases, can I somehow use a profiler to determine improvement or do I have to resolve to other options?

答:
once I decide what I want to optimize it might be problematic to see
  the improvement in numbers.

One has to wonder whether you've really found a bottleneck, and also whether you've really eliminated one, if you can't see the effect in the profiler.

This is especially true in desktop apps which run constantly and it is
  difficult to: execute the same path and execute it the same number of
  times to have reliable comparison.

This is one of the things that unit tests can help you with. You should be able to recreate any situation that interests you in a test, even (especially!) those which might be very difficult to replicate in the wild. You can also repeat that test as many times as you want to. If you run the profiler against your test, then, you should be able to see the effect of whatever improvements you make. If you can't measure the effect of the improvement, you really have no grounds for claiming that you've improved the code at all.


问:
Always pull out common cases and branch separately?
We had a disagreement in a code review.

What I had written:

```<code>if(unimportantThing().isGood && previouslyCalculatedIndex != -1)
{
    //Stuff
}
if(otherThing().isBad && previouslyCalculatedIndex != -1)
{
    //Otherstuff
}
if(yetAnotherThing().isBad)
{
    //Stuffystuff
}
</code>```

The reviewer called that ugly code. This is what he expected:

```<code>if( previouslyCalculatedIndex != -1)
{
    if(unimportantThing().isGood)
    {
        //Stuff
    }
    if(otherThing().isBad)
    {
        //Otherstuff
    }
}
if(yetAnotherThing().isBad)
{
    //Stuffystuff
}
</code>```

I'd say it's a pretty trivial difference and that the complexity of adding another layer of branching is equivalently bad as one or two logical-ands.

But just to check myself, is this really a grievous coding sin that you would take a firm stance over? Do you always pull out the common cases in your if statements and branch on them separately, or do you add logical-ands to a couple of if statements?

答:
This is pretty minor, but I'd say you're wrong. The main reason why his code is better is because previouslyCalculatedIndex != -1 is only done once. This isn't any kind of performance optimization, but if you ever have to change that condition to say -2 or some such, then you only have to change it in one place instead of two. And, if you continue the pattern (say you had 10 other things which relied on the index being -1), then eventually it would be a huge amount of references to update.

Again, pretty minor, but the reviewer is right. His way is cleaner and has less duplication and will in the long run be easier to maintain. Also, in my opinion, it looks a bit more clear

Also, for your edited in questions(I think). It's an opinion as to if this should be done with 1 if statement (I tend to not), but if you have two, then you do should it like this. What about when you have to go add some feature a year from now and have to add a condition that relies on index being -1. Then, you'll either have to continue the code duplicatation, or take the time to refactor it to how your coworker said it should be in the first place


答:
There are two reasons I would prefer the second over the first. The first is repetition: You repeat yourself which can lead to more difficult to maintain code. The second is that I think the second is more clear on when each block of code is executed. If I am debugging and I know that  previouslyCalculatedIndex != -1
, then I can immediately skip two whole blocks of code in the second one by just checking one conditional. In the first, I am forced to check two conditionals. Double the work for the same outcome.

Another thing to consider is that if statements are a big place to cause bugs. The longer the conditionals (the more && and || you use), the more chances you have of creating a bug by getting it wrong. Reducing the complexity of your conditionals can make it easier to understand later as well.

Title: Always pull out common cases and branch separately?

Body:
We had a disagreement in a code review.

What I had written:

```<code>if(unimportantThing().isGood && previouslyCalculatedIndex != -1)
{
    //Stuff
}
if(otherThing().isBad && previouslyCalculatedIndex != -1)
{
    //Otherstuff
}
if(yetAnotherThing().isBad)
{
    //Stuffystuff
}
</code>```

The reviewer called that ugly code. This is what he expected:

```<code>if( previouslyCalculatedIndex != -1)
{
    if(unimportantThing().isGood)
    {
        //Stuff
    }
    if(otherThing().isBad)
    {
        //Otherstuff
    }
}
if(yetAnotherThing().isBad)
{
    //Stuffystuff
}
</code>```

I'd say it's a pretty trivial difference and that the complexity of adding another layer of branching is equivalently bad as one or two logical-ands.

But just to check myself, is this really a grievous coding sin that you would take a firm stance over? Do you always pull out the common cases in your if statements and branch on them separately, or do you add logical-ands to a couple of if statements?


答:
While it looks like the two blocks of code are the same, there is the possibility that they are not.  In particular, if stuff modifies previouslyCalculatedIndex the code paths for the two may be different.

This is likely not something that is intended to happen, but it could.  The first example would expose a bug if the shared conditional variable was to change.  The second example prevents this from happening (the conditional is only tested once).

For readability, I find the second example easier to read.  I am aware of the scope that the outer if statement has and can read the less complex if statements more easily.

Few rules are 'always' - I doubt that any but the most pedantic always do anything when it comes to code style.  However, when possible, one should attempt to code as defensively (writing code that is hard to modify in the wrong way) and understandable as possible.

When things get to the complexity of 5-10 conditions, this is something that needs even more drastic refactoring - extracting methods (both for the conditional and the common code).

Consider how complex the class is when you do get to 5-10 conditions.  Additional complexity is correlated to increased bug counts (and more difficult testability).

Take steps early on to keep the complexity low.


问:
Encapsulate external JavaScript library
I am about to develop a ASP.NET MVC 4 project that will make use of maps. Our company has it's own map API which is very basic at the moment, but is intended to be further developed in future to match some specific customer needs.
The project will have a mobile/tablet interface in addition to it's web interface and needs to be developed now. So we have planned to start use the Google Maps v3 API.

I would like to encapsulate the API, so our applications don't have Google API specific calls. The same approach as if I would like to use som external API i C# and wanted to encapsulate it in order to be able to switch API in future without having to re-code the entire application.

But I haven't been able to find similar examples, so the following questions arise:

Is it a good and reasonable approach? Let me hear your pros and cons.

How would it be done in practice?

答:
If you want to simplify the first layer of the front-end development of your application, it does sound like a good and reasonable approach (if well-designed: it improves maintainability, scalability, etc.).

I believe that you want to implement a FACADE, this article here should explain just what you need:
http://www.joezimjs.com/javascript/javascript-design-patterns-facade/

You can define the Facade pattern as a piece of code that simplifies a
  more complex interface. You can pretty much call any form of
  abstraction a facade.

Title: Encapsulate external JavaScript library


答:
Is it a good and reasonable approach? Let me hear your pros and cons.

Typically, I would advise against preemptively encapsulating a library or API - it's usually a bad case of YAGNI, as it complicates your design for dubious gains. Most of the time what happens is that the wrapper ends up being tied too closely to what it's encapsulating, so that even when you actually do end up switching to some other library or API, you have to change all the client code because the new one is too different and matches very badly to your wrapper.

In this case, it might be defendable as you have relatively concrete plans of switching the underlying API and already a second implementation, albeit an incomplete one. If you do it, I would very much recommend looking closely at at least one other complete map API (like Bing Maps) to ensure your API could work with it.

How would it be done in practice?

The best approach is probably indeed a facade: don't try to write a wrapper that exposes all the functionality of Google Maps. Instead, create an interface that contains only the map-related functionality your application needs and thus represents an abstraction layer. It will probably aggregate calls as well as translating them and contain some logic of its own.

Your chances of porting it to a different map provider without having to change the application code are much better than with a thin, fully-featured wrapper.

Title: Encapsulate external JavaScript library

Body:
I am about to develop a ASP.NET MVC 4 project that will make use of maps. Our company has it's own map API which is very basic at the moment, but is intended to be further developed in future to match some specific customer needs.
The project will have a mobile/tablet interface in addition to it's web interface and needs to be developed now. So we have planned to start use the Google Maps v3 API.

I would like to encapsulate the API, so our applications don't have Google API specific calls. The same approach as if I would like to use som external API i C# and wanted to encapsulate it in order to be able to switch API in future without having to re-code the entire application.

But I haven't been able to find similar examples, so the following questions arise:

Is it a good and reasonable approach? Let me hear your pros and cons.

How would it be done in practice?


问:
Should object oriented programming be the first thing students learn?
My high school is starting a program where, instead of following the 'traditional' method of teaching programming (learning variables, then operations, loops, methods, and finally OOP), students are immediately introduced to object oriented programming without any other programming knowledge.

Is this a good idea?

My personal view is that teaching OOP first is misguided - when I was introduced to OOP, I was able to appreciate the power it gave me when designing complex programs, as I was already familiar with procedural programming. Introducing students to OOP at such an early stage might make them ignorant as to the power and flexibility that OOP gives programmers.

There are also the practical problems - students might have a difficult time designing classes when they have not been introduced to methods properly (how they work, when they should be used, etc.). I don't have many details about the course curriculum, but by my understanding, students are to be introduced to OOP by their third lesson, after having been taught variables and operations (as well as standard input/output).

In case it's relevant, the language my school teaches in is C#.

答: I believe it's a bad idea to teach object oriented programing first. My friend who took a course at a university where they taught OOP right away didn't properly learn how things worked. I believe not focusing on paradigms and not using classes is a good approach to introducing programing. Get familiar with the primitive data structures and flow control before learning OOP specific features.</p>


问:
When to use nested resources in a RESTful API
I have two resources: users and links.

Users can have several links associated with them. I have designed my RESTful API so that you can reach the links associated with a user at the following URI:

/users/:id/links

However, I always need to have a URI for just links – sometimes I might want all links, regardless of user.

For this I have:

/links

Does this sound okay? Having two URIs for links?

I wonder if I should instead reach the links for a user with a URI such as:

/links/user/:id or /links/?user=:id

This way, I only have one resource for links.

答:
No, there is nothing wrong with having multiple resources for the same "thing", in this case lists of links.

We were recently struggling with the same problem. Our decision was to have all resources where there is not a strict ownership not to be nested. In other words, the links would be modeled under

```<code>/links -- all links
/links/:linkid -- a particular link
</code>```

Then, filters on the links collection are expressed as query parameters. So to get the links of a certain user, you would use:

```<code>/links?user=/users/:userid
</code>```

This also allows for easier composition of filters:

```<code>/links?user=/users/10&since=2013-01-01
</code>```

And it is easy to understand conceptually - you have a collection of items, and you add filters to it.

That being said, there is nothing more "RESTful" about this approach than any other URI naming scheme. It's just a convention we found human-readable and easy for us developers to understand and embrace. REST doesn't care about what you put in your resource identifiers.

Body:
No, there is nothing wrong with having multiple resources for the same "thing", in this case lists of links.

We were recently struggling with the same problem. Our decision was to have all resources where there is not a strict ownership not to be nested. In other words, the links would be modeled under

/links -- all links
/links/:linkid -- a particular link

Then, filters on the links collection are expressed as query parameters. So to get the links of a certain user, you would use:

/links?user=/users/:userid

This also allows for easier composition of filters:

/links?user=/users/10&since=2013-01-01

And it is easy to understand conceptually - you have a collection of items, and you add filters to it.

That being said, there is nothing more "RESTful" about this approach than any other URI naming scheme. It's just a convention we found human-readable and easy for us developers to understand and embrace. REST doesn't care about what you put in your resource identifiers.


答:
I really think not.

Like many programmers of my generation, I learned using BASIC as a child, and I still think it has tremendous advantages over other more "modern" languages for those who are just starting to learn.

I think it may depend upon existing exposure and age (and what do you mean by the first thing they learn - kids as old as 2 or 3 are playing with tablets all the time now), but I have not seen any studies which looked at this at any age.

From a usability perspective for real neophytes, I think things like Python's white space and semicolon requiring languages (or JavaScript's automatic semicolon issues) can be a hindrance, but again, it depends upon their other experience to computers and keyboards etc.

I think a big mistake of people talking about the language to be taught is that they approach learning programming from the language at all instead of more holistically about all the gaps in people's computer experience.  Some beginners are not familiar with the computer, or the names of special characters, etc.  I expect this is actually GROWING rather than declining with the diminishing exposure to desktop computers in the home and decline of laptops compared to tablets among kids.  I remember early computing courses I attended (talking TRS-80 days again) concentrated on flow charts, but that seems to have completely gone out of vogue.

Title: Should object oriented programming be the first thing students learn?

Body:
My high school is starting a program where, instead of following the 'traditional' method of teaching programming (learning variables, then operations, loops, methods, and finally OOP), students are immediately introduced to object oriented programming without any other programming knowledge.

Is this a good idea?

My personal view is that teaching OOP first is misguided - when I was introduced to OOP, I was able to appreciate the power it gave me when designing complex programs, as I was already familiar with procedural programming. Introducing students to OOP at such an early stage might make them ignorant as to the power and flexibility that OOP gives programmers.

There are also the practical problems - students might have a difficult time designing classes when they have not been introduced to methods properly (how they work, when they should be used, etc.). I don't have many details about the course curriculum, but by my understanding, students are to be introduced to OOP by their third lesson, after having been taught variables and operations (as well as standard input/output).

In case it's relevant, the language my school teaches in is C#.


问:
Why do we need the async keyword?
I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler knows a method awaits something. But it seems like the compiler should be able to figure this out without a keyword. So what else does it do?</p>

答:
it changes the method from a normal method to a object with callback which requires a totally different approach for code generation

and when something drastic like that happens it is customary to signify it clearly (we learned that lesson from C++)

Title: Why do we need the async keyword?


答: I think there are many ways to teach programming, it really depends on the course content and the teacher, they may have a really good approach to teaching the concepts.  I don't think you can really judge the quality of approach without knowing the whole story.   This question feels like it is asked with a bias of expectation, highlighting how it can fail based on that expectation,  rather than perhaps the course creators vision of how they want to build the concepts and teach.</p>


答: The whole idea with keywords like "async" or "unsafe" is to remove ambiguity as to how the code they modify should be treated. In the case of the async keyword, it tells the compiler to treat the method modified as something that does not need to return immediately. This allows for the thread where this method is used to continue without having to wait on the results of that method. It's effectively a code optimization.</p>

Title: Why do we need the async keyword?

Body: I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler knows a method awaits something. But it seems like the compiler should be able to figure this out without a keyword. So what else does it do?</p>


答:
I believe that there are at least two levels of writing code:

writing code that does the task that it is supposed to do;

writing maintainable code that does the task and is also maintainable.

According to me, OOP is mainly about writing maintainable and understandable code. I think that when you learn programming it is hard enough to write code that just does what it has to do. This does not mean that writing clean, structured, and object oriented code is less important, it just means that it is too early to speak about that problems.

I would not introduce OOP concept in an early stage of learning of programming, because you can appreciate the advantages of OOP only after having written at least medium size programs.


答:
I think C# is an excellent choice. You can get some pretty cool applications up and running with minimal knowledge. OO programming is not very different, if not identical to procedural programming in many ways. The students will still have to learn procedural style programming when they implement methods, but they will get to make much more interesting programs because they can make use of existing classes and/or overriding methods in those classes.

The trick at high school level is not to teach the students the ins/outs of programming but instead to get them "hooked" on programming. If they can build a really cool graphical application that does some neat things but learn only very basic programming, that will go a lot further than teaching them procedural coding but they have to use the console window that only allows textual input/output like they would end up doing if they started using a procedural language.

There are probably very many potential good programmers who lost interest after having to work with just cin, cout, scanf and getch().


答:
I think is a good idea because maybe then they won't write procedural code in a OO language as many programmers do. Of course they will not write good code from start or understand the concepts deeply but they will in time. Probably they will see it natural to use polymorphism and strategy pattern instead of many if-elses or switch.

Regarding procedures I believe is a good idea to learn with the idea of encapsulation from start; in OOP your procedures (methods) are not global and do no access global data so your are more restricted when writing them. If one learns this as a native and proper way, it will probably write better code with fewer dependencies.

However I believe OOP is probably better suited for university not for highschool.


答:
I was teaching an introductory course to programming a while ago. In order to prepare my class, a few months before starting, I read a great book named:

Reflections on the Teaching of Programming: Methods and Implementation.

The book covers research about different approaches to teaching programming on different universities during a long period. This includes techniques as objects first, functional programming first, apprentice-learning, model driven, etc., etc.

I defintely think it is a good start to get a good answer to your question.

Now a great book on how to teach objects first is Objects First with Java: A Practical Introduction Using BlueJ.

The book is very well designed thinking on teachers and students. Your lessons are already well prepared and I like the approach, even when I did not use it.

I taught my class first using an imperative style with Python and then, in a second class, I moved to the object-oriented model, mostly using the Karel The Robot: A Gentle Introduction to the Art of Programming and the students loved it. I think I could have tought programming with the object-first aproach using any of these two books. Evidently, these are for introductory courses. And some videos of University of Standford that I have seen seems to use these same approach.


答:
I think context matters. I prefer to allow the important things stand out and they should be foremost in your if tests.

From your example, if the isGood/isBad is what your if-checks are really trying to capture and the previouslyCalculatedIndex is simply a check to make sure you can validly take the appropriate action then I might go with a 3rd approach and put the if(previouslyCalculatedIndex != -1) inside the isGood/isBad braces for each check, since whether you can validly process the isGood/IsBad condition is secondary to what you were really trying to capture (that being isGood/isBad).

Also, what if you want to create a log entry if(previouslyCalculatedIndex == -1) and your isGood/isBad condition was met? None of the other suggestions help with that situation because they are trying to save a line of code instead of making the code more understandable.

I would also change -1 to a const with a meaningful name.

On the other hand, if(previouslyCalculatedIndex != -1) is the important test, then the 2nd option is better.


问:
How to write useful Java programs without using mutable variables
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

答:
How to write useful Java programs without using mutable variables.

You can in theory implement just about anything in Java using just recursion and no mutable variables.

In practice:

The Java language is not designed for this.  Many constructs are designed for mutation, and are hard to use without it.  (For instance, you can't initialize a variable length Java array without mutation.)

Ditto for the libraries.  And if you limit yourself to library classes that don't use mutation under the cover, it is even harder.  (You can't even use String ... take a look at how hashcode is implemented.)

Mainstream Java implementations don't support tail-call optimization.  That means that recursive versions of algorithms tend to be stack space "hungry".  And since Java thread stacks don't grow, you need to preallocate big stacks ... or risk StackOverflowError.

Combine these three things, and Java is not really a viable option for writing useful (i.e. non-trivial) programs without mutable variables.

(But hey, that's OK.  There are other programming languages available for the JVM, some of which do support functional programming.)


问:
Table scaling with partitions or with separate databases?
Hypothesis: I have a table (named BigTable) which could experience 5,000,000 INSERTS per day (with possibly just as many SELECTs).  Each row inserted is about 50kb.

These daily INSERTs are split across 5 clients equally (the table has a FK called ClientID). There is never a need to SELECT or JOIN data across multiple clients.

I am worried about the database performance as this table grows, so I have come up with three solutions.

SOLUTION 1:

Partition BigTable by ClientID

Store each partition on a separate hard disk on the server (using Azure blob storage).

Partition all data which is 1 month old (archive data, yet still need to be queryable) into another set of READONLY partitions.

Essentially this means the following partitions on their own storage devices:

Primary (all data excluding BigTable)

ClientA's BigTable (5,000,000 rows per day / 5 clients x 30 days = 30,000,000 rows)

ClientB's BigTable (30,000,000 rows)

ClientC's BigTable (30,000,000 rows)

ClientD's BigTable (30,000,000 rows)

ClientE's BigTable (30,000,000 rows)

ClientA's BigTable archive

ClientB's BigTable archive

ClientC's BigTable archive

ClientD's BigTable archive

ClientE's BigTable archive

The number of rows in the archive tables will be (5,000,000) x (age of DB in days) - (30,000,000).  This is still a huge table, but will only be used to drawing up the odd report.

SQL Server will be hosted on a 14GB, 8 core Azure VM.

SOLUTION 2:

The other option is to host separate databases for each client.  This means each will have it's own dedicated SQL Server machine.  Partitioning will still happen for archive data.

This option is not optimal because of the physical separation of the data.  Having to manage updates to multiple databases could be very problematic.  Having separate database connections for each client will also be a consideration for the developers.

Could anyone perhaps advise on these options?

SOLUTION 3:

Archive data into a faster database platform.  I don't know much about this, but perhaps a NoSQL database could handle billions of records much better than SQL Server?

答:
I would go with Option 2..

You most certainly don't need a dedicated SQL Server machine for each client, you don't even need and dedicated Instance. I don't know you think that is the case.

My primary reason for this is that when the time comes that you want to scale horizontally (more servers) this is going to best position you to do that.

I don't understand why you think that to "manage updates to multiple databases could be very problematic".  Dealing with different Db connections is trivial, i don't understand this concern either. All of this is particular true because "There is never a need to SELECT or JOIN data across multiple clients."

Additional Note : You can still partition the individual Client DBs (by date or something) should you choose\need to do so.

ContentLicense: CC BY-SA 4.0


问:
Design Parts DB
I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on...

In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...).

I am thinking of 3 different DB designs:

Using a parts table and derived tables for specialized part attributes.

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, lenght, diameter, material)
Contacts   (id, part_id, description, picture)
</code>```

Using only specialized part tables.

```<code>Wires      (id, name, lenght, diameter, material)
Contacts   (id, name, description, picture)
</code>```

Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.

```<code>PartTypes  (id, name)
ValueTypes (id, part_type_id, name)
Parts      (id, part_type_id, name)
PartValues (part_id, value_type_id, value)
</code>```

Which one to prefer and why? Or is there a better one?

I am concerned about the DB queries. I don't want the queries become overly slow or complicated.

Update

The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.

答:
Definitely go with option 1 but with a few very simple modifications:

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, part_type_id, lenght, diameter, material)
Contacts   (id, part_id, part_type_id, description, picture)
</code>```

You can then use CHECK constraints and DEFAULT values to ensure that the part_type_id is correct, and then you can join on both part_type_id and part_id.  This avoids having a conditional join based on only one table, and if you need to add a part_type_id to wires (say we are subdividing that part and adding another table of extended attributes) the default and check constraints can be changed.

Title: Design Parts DB

Body:
Definitely go with option 1 but with a few very simple modifications:

Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, part_type_id, lenght, diameter, material)
Contacts   (id, part_id, part_type_id, description, picture)

You can then use CHECK constraints and DEFAULT values to ensure that the part_type_id is correct, and then you can join on both part_type_id and part_id.  This avoids having a conditional join based on only one table, and if you need to add a part_type_id to wires (say we are subdividing that part and adding another table of extended attributes) the default and check constraints can be changed.


问:
Count true array elements
In my code (Python+numpy or Matlab, but issue can apply to any array programming language), I often need to count the number of elements in an array where the elements are true. Usually, I implement this as sum(x>0.5), but this may be considered improper. See Is it correct to add booleans in order to count the number of true values in a vector?. Numpy has count_nonzero, but if there is no special-purpose function, what would be the proper way to write this?

For example, in Matlab, I can either write sum(x>.5) or length(find(x>0.5)). The former is slightly faster but may be considered improper (see above). Are there any other alternatives for counting the number of true values in an array, and what should be my criteria for selecting one?

(In a low-level language, one would write an explicit for-loop, but that is an extremely inefficient way to implement this in a high-level array programming language)

答:
It seems like if you want to count the true elements, you probably want to get the true elements in some other context.  Also, getting the true elements and then counting them reads nicely, in my opinion.

My python is rusty, but this will give you the general idea:

```<code>def take_true(list):
  return [x for x in list if x]

def true_count(list):
  return len(take_true(list))
</code>```

Title: Count true array elements

Body:
It seems like if you want to count the true elements, you probably want to get the true elements in some other context.  Also, getting the true elements and then counting them reads nicely, in my opinion.

My python is rusty, but this will give you the general idea:

def take_true(list):
  return [x for x in list if x]

def true_count(list):
  return len(take_true(list))


问:
Is a merging strategy like Git Flow really an anti-pattern?
My company is using Git, and is using a peculiar branching scheme - work is done in master, and branches are reserved for releases.  This works fine, so long as all of the work done in an iteration makes it into the branch, but if a critical production issue comes up, we have to ensure that the work somehow makes it into both branches.

Lately, we've been having some "fun" with those branches.  It's been an administrative headache, ensuring that all of the work makes it into every branch, and some bugs which have been fixed on one branch don't make it into master until someone points it out, which is concerning.

I came across Git Flow a while back, and I feel that it would be a solution to our problem - code not percolating all the way to the release, or all the way back down.  The only catch is that my lead stated that this sort of development was an anti-pattern - developing furiously for two weeks, then spending three to resolve the merge conflicts.

I'm not entirely sure I agree, and since I brought it up, work has resumed like normal.  Only recently have we had some major pain points with this.

I'd like to know - why would this sort of development scheme be seen as an anti-pattern?  Is it really an anti-pattern?

答:
He's mostly referring to the feature branches side of the model.  Feature branches were declared an anti-pattern a long time ago when the branches lasted for months and version control systems couldn't merge to save their life.  Feature branches that last a week or two have much fewer issues, especially if you're continually merging from develop into the feature branch during that time.  Anything much longer than that is still not recommended.

Even if you don't use the feature branch side of git flow, the other parts are useful in ensuring you get clean merges and your changes are propagated in the right direction.


答:
Merging is a funny thing - the less frequently it's done the harder it will be, the harder it is, the more people will be afraid of it, the less frequently they will do it.

Solution is either do not allow branches to deviate too much, or not to use branches.

If people understand this, you will probably have not much problems with merge, if not - may be branches are not a good idea without some education.

Title: Is a merging strategy like Git Flow really an anti-pattern?

Body:
My company is using Git, and is using a peculiar branching scheme - work is done in master, and branches are reserved for releases.  This works fine, so long as all of the work done in an iteration makes it into the branch, but if a critical production issue comes up, we have to ensure that the work somehow makes it into both branches.

Lately, we've been having some "fun" with those branches.  It's been an administrative headache, ensuring that all of the work makes it into every branch, and some bugs which have been fixed on one branch don't make it into master until someone points it out, which is concerning.

I came across Git Flow a while back, and I feel that it would be a solution to our problem - code not percolating all the way to the release, or all the way back down.  The only catch is that my lead stated that this sort of development was an anti-pattern - developing furiously for two weeks, then spending three to resolve the merge conflicts.

I'm not entirely sure I agree, and since I brought it up, work has resumed like normal.  Only recently have we had some major pain points with this.

I'd like to know - why would this sort of development scheme be seen as an anti-pattern?  Is it really an anti-pattern?


问:
How to convince my teammates to follow some basic rules
I have a problem with my teammates. Long story short: We are three students working at a project for a competition. The project consists of 2 separate applications: one for Windows (that I develop) and one for Android (my colleagues are responsible for developing it). Our code bases will never intersect, the apps will communicate via third party tools.

The problem is as follows: I have some experience working in teams as I made an internship at a big company last year, and I try to enforce some coding standards for our code. I also set up a git repository / wiki / collaboration software that we can use to push code / write ideas, document protocols and so on, but it seems that I am the only one that uses these tools.

I tried to tell them that writing quality code and documenting every step will benefit us in the long run, but they don't seem to see the advantage of it. Also I was thinking to add some integration tests but from what I can see, as long as they don't use current tools to make their life easier, I don't think I can convince them the usefulness of integration tests.

Most of the peer's code resides on their computers, they don't share a common code base and as I found out, they integrated their pieces by meeting and sharing code via usb stick.

My question is: am I too harsh on this matter? Do I enforce some absurd rules? Keep in mind that this is a small project, the requirements are very clear(I created documents specifying what should the applications do), three skilled developers could do this in 3-4 days, so they might not see the added complexity of writing quality code as long as their current method just works.

Is there any way that I can show them the benefit of documenting code, using git and so on?

答:
My attitude is that if you can learn to do these things on small projects, you'll be prepared when big projects come along.

If they follow good development practice with this project, they will have code to showcase to future employers, and they will have experience that would make them valuable as employees.

If you want more material for convincing them, I would refer to the Pragmatic Programmer, or Code Complete.

On the other hand, consider cutting them some slack. If the project is a proof-of-concept that is getting binned right after the competition, then you should consider just letting them do as they like. They might be struggling just to write the code in the first place, without the mental overhead of good practices.


答:
My question is: am I too harsh on this matter?

You can lead a horse to water, but you can't make him drink.

It's hard to say whether you're "too harsh," but it may be unrealistic to expect your teammates to adopt all the infrastructure that you're hoping for. And truly, if the team is working well together, using a wiki to communicate between three people is probably overkill.

Scale back your expectations and look for ways to achieve some of your goals without requiring them to start using tools that they don't know. If they don't know how to use git, they're probably not going to get a lot of benefit from it in any case. However, you still want to make sure that all code is backed up in case of a hard drive failure or other catastrophe, so ask them to periodically copy their project folder to a Google Drive, Dropbox, or similar online file sharing service. Make sure you do the same.

Title: How to convince my teammates to follow some basic rules

Body:
I have a problem with my teammates. Long story short: We are three students working at a project for a competition. The project consists of 2 separate applications: one for Windows (that I develop) and one for Android (my colleagues are responsible for developing it). Our code bases will never intersect, the apps will communicate via third party tools.

The problem is as follows: I have some experience working in teams as I made an internship at a big company last year, and I try to enforce some coding standards for our code. I also set up a git repository / wiki / collaboration software that we can use to push code / write ideas, document protocols and so on, but it seems that I am the only one that uses these tools.

I tried to tell them that writing quality code and documenting every step will benefit us in the long run, but they don't seem to see the advantage of it. Also I was thinking to add some integration tests but from what I can see, as long as they don't use current tools to make their life easier, I don't think I can convince them the usefulness of integration tests.

Most of the peer's code resides on their computers, they don't share a common code base and as I found out, they integrated their pieces by meeting and sharing code via usb stick.

My question is: am I too harsh on this matter? Do I enforce some absurd rules? Keep in mind that this is a small project, the requirements are very clear(I created documents specifying what should the applications do), three skilled developers could do this in 3-4 days, so they might not see the added complexity of writing quality code as long as their current method just works.

Is there any way that I can show them the benefit of documenting code, using git and so on?


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
I say that for anything but a trivial web application, you should version it.  There are two, slightly different, notions at work here:

application as a whole

individual files

Regardless of the situation, I believe that files should have individual version (or revision) numbers.  Ideally, this would be handled automagicaly by your version control system.  As it has been stated by others, it's easier to refer to a file's version number than its date-and-time.

If you have (or may have) more than one live installation of the application, it should be versioned as a whole.  This is also a good practice if you have separate dev and test environments (as you likely should).  Each application (or release) version number refers to a collection of individual files at specific version numbers.  While dealing with all of this is an extra burden, it is easier to check-out a specific release than individual files at specific revision numbers.

This makes me think of a notion in linguistics.  It is said that if you can't express something in a language, you can't think about it (in that language).  I think of the German word 'Schadenfreude.'  It is much easier to think (and speak) of this notion of "feeling joy due to someone else's misfortune" by referring to that word, than its definition.  That is the reason the word has crept into use in the English language.

Similarly, version numbers make it easier to speak (and think) of your application and its files at specific states.  If you're a one person team, working on one application, it doesn't likely make a huge difference.  However, as things get more complicated it is better for you to have these labels available for use.

ContentLicense: CC BY-SA 2.5

Title: Should you version web applications?


答:
Documentation, Wiki, versioning software, methodologies etc are experiences and lessons learned over time; working of several projects and probably over several teams. And it usually sticks with those already employed or who take their industry seriously.
They are students, so their interests are probably limited short of what happens in the future. :)

But to try and answer your question:

If you are in a team with them you would need to apply what you think is important in a way that benefits their interests. As an example : Should they complain about their code breaking a lot when the usb-share it? Then perhaps give them a simple (non complicated) way of using SVN (rather than git) as a versioning tool.

I also agree with the comment from arnaud.

You saw the benefit of all these tools when you were working with them and that is how you saw value in them and why you understand their use. If your team mates do not see a value added in how they currently do things, then they will not apply it. And the sad thing is this even counts for teams made of people with any level of experience.


问:
Re-engineering an ASP.NET AJAX project as ASP MVC
I have been asked to investigate the possibility of re-engineering an existing ASP.NET AJAX Web Application as under MVC.

The project, as it stands ATM, is very heavily relient on Telerik's ASP.NET AJAX controls.

I've yet to have to opportunity to interview the person responsible for this request, so I'm unsure of the drivers for this, but I believe that as well as looking for a more structured solution (the original was developed in a very organic way) I believe that one of the goals is to also get a lot of the code running client-side and to use a structured form for the development there also.

So, My question is, is there a defined set of considerations for something like this? Or, if people do this kind of thing at all, do they just wing it?

答:
When we started the migration of our project to a more MVC-oriented style, we were also using Telerik Ajax. We wanted the project to be shippable during the migration, so we first refactored the code to fit the MVC pattern, then switched the framework.

The pattern switch was implemented by relying heavily on WebMethod to populate our views, replacing the ASP.NET and Telerik components with pure HTML and Javascript, and completely stop relying on ViewState.

You then just need to modify the Views, and the rest should mostly fit.


答:
I'm afraid the rules you described aren't basic at all.

The easiest task IMO is convincing your teammates to use some coding standards. And a simple way to achieve this is to show them the same code snippet once well-formatted and then poorly-styled, ask them to read the code, understand what it does and let them judge themselves.

What comes to using a git repository, this can be a pain to novices. When I was working in a team of 3 people on an Android project, we had a lot of trouble with our version control system at first. So I expect your teammates will have the trouble too.

You've mentioned that it would take 3-4 days for experienced developer to finish the project (I assume that it would take your team 2-3 times as long). This is a very short period of time, so the argument that using new tools will help in the long run simply won't work.

What you can do is make short and simple demos to show how those tools are used. Cover the most basic functions at first, sit by their side and help them use the tools. Be prepared to do all the tasks like configuring the git, creating the wiki page structure, etc.

Edit: In reply to the comment, I think that establishing clear tasks, estimations and deadlines and keeping track of the time spent is more important than using git or similar tools. If you plan to work on the application later, it is very important to keep a track what is already done and how long each feature took. So I suggest you start from task management, and then proceed to the tools you want to use.


问:
How do I learn algorithms and data structures?
This is in continuation to my previous question where I asked is it necessary to learn algorithms and data structures. I feel yes it is.

Now I work in an environment where I won't ever get the chance to learn it by experimenting or practically or in any assignment. What is the right approach like the right books, right kind of problems, right kind of resources that I can go through to give six months or a year or two to learn algorithms and data structures?  And also mold my mind in a way that it can relate problems to data structures and algorithms.

答:
Algorithms

I took magic lessons in a group setting when I was twelve years old. The magician's name was Joe Carota. He did a trick one time and I blurted out, "How did you do that?" He said something that day that has stuck with me ever since.

Joe's response, "Michael, if you really want to know how that trick is done you must figure out how you would do it yourself."

Well of course that's not what I wanted to hear but it did get my mind focused on problem solving. This was problem solving from my perspective. If my first attempt at solving the problem took seventeen steps and was really klunky, the good news was I solved the problem.

Then by looking at the solution I had developed and looking for ways to refine that solution I would learn how to streamline the end result. Later on in my computer programming life I found out that this process was called "Stepwise Refinement". I think today they call it refactoring.

It worked then it still works now.


问:
Addition vs multiplication on algorithm performance
I am studying about optimizing alogrithms.(Prof. Skiena's Algorithm Guide book)

One of the exercises asks us to optimize an algorithm:

```<code>Suppose the following algorithm is used to evaluate the polynomial
p(x) = a^(xn) + a^n−1(xn−1) + . . . + a(x) + a
p := a0;
xpower := 1;
for i := 1 to n do
xpower := x ∗ xpower;
p := p + ai ∗ xpower
end
</code>```

(Here xn, xn-1... are the names given to distinct constants.)

After giving this some thought, the only way I found to possibly improve that algorithm is as follows

```<code>p := a0;
xpower := 1;
for i := 1 to n do
  xpower := x ∗ xpower;
     for j := 1 to ai
         p := p + xpower
     next j
next i
end
</code>```

With this solution I have converted the second multiplication to addition in a for loop.

My questions:

Do you find any other way to optimize this algorithm?

Is the alternative I have suggested better than the original? (Edit: As suggested in the comments, this question though related to the problem deserves another question of its own. Please ignore.)

答:
The standard solution is to notice that one has many multiplications with the same number x.

So instead of

```<code>p(x) = a_n*x^n + a_n−1*x^n−1 + . . . + a_1*x + a_0
</code>```

one might write

```<code>p(x) = (...((a_n*x) + a_n−1)x + ... + a_1)*x + a_0
</code>```

Perhaps easier to read:

```<code>p(x) := a_3*x^3 + a_2*x^2 + a_1*x + a_0
q(x) := ((a_3*x + a_2)*x + a_1)*x + a_0
p(x) == q(x)
</code>```

We call such evaluation Horner's method. It translates to approximately:

```<code>p := a_n;
for i is n-1 to 0
   p := p*x + a_i
</code>```

Horner's method has n multiplications and n additions and is optimal.

Body:
The standard solution is to notice that one has many multiplications with the same number x.

So instead of

p(x) = a_n*x^n + a_n−1*x^n−1 + . . . + a_1*x + a_0

one might write

p(x) = (...((a_n*x) + a_n−1)x + ... + a_1)*x + a_0

Perhaps easier to read:

p(x) := a_3*x^3 + a_2*x^2 + a_1*x + a_0
q(x) := ((a_3*x + a_2)*x + a_1)*x + a_0
p(x) == q(x)

We call such evaluation Horner's method. It translates to approximately:

p := a_n;
for i is n-1 to 0
   p := p*x + a_i

Horner's method has n multiplications and n additions and is optimal.


问:
Cheap programmable, portable device
Since a long time I have thrived for being able to program something I can take with me - a very small computer like a programmable calculator, gameboy, pocket PC or cellphone.
However, I didn't find anything fitting yet!

The thing I'm looking at is the price, because I can't afford to spend too much money on it.

What are some cheap portable programmable devices?

All I'd need is support for uploading assembler code from my computer. I don't care about the display, a simple LCD would be sufficient. Same goes for the buttons

I have looked at programmable calculators, portable gaming consoles such as the PSP and more, however didn't find anything that fit :(

答:
If something you can take with you, but not really for using on the move, take a look at Raspberry Pi.

You can use it on the move with a USB power pack designed for giving your cellphone extra battery life, but you'll also need to bring some sort of screen / output device with you, and maybe a USB keyboard or something.

OwnerDisplayName: Ars

Title: Cheap programmable, portable device


答:
In your position i would buy a cheap Android-Tablet (you can get them for under 100€/$)
and then code with AIDE, it's an IDE to develop full Android-Apps on Android devices with Java.</p>

Title: Cheap programmable, portable device

Body:
Since a long time I have thrived for being able to program something I can take with me - a very small computer like a programmable calculator, gameboy, pocket PC or cellphone.
However, I didn't find anything fitting yet!

The thing I'm looking at is the price, because I can't afford to spend too much money on it.

What are some cheap portable programmable devices?

All I'd need is support for uploading assembler code from my computer. I don't care about the display, a simple LCD would be sufficient. Same goes for the buttons

I have looked at programmable calculators, portable gaming consoles such as the PSP and more, however didn't find anything that fit :(


答:
Whilst I don't know much about Ajax controls (I am currently working on an intranet based MVC application), I would advise the use of Razor markup if you are looking to implement a lot of client-side code.

Basic Introduction to Razor here

Depending on your development environment too, in my (admittedly limited) experience Razor has proven to be incredibly useful and easy to use.

The link above justifies the use of Razor itself better than I could, so I will let it do the talking. Suffice it to say Razor led to an easier life creating Views in MVC.

Title: Re-engineering an ASP.NET AJAX project as ASP MVC

Body:
I have been asked to investigate the possibility of re-engineering an existing ASP.NET AJAX Web Application as under MVC.

The project, as it stands ATM, is very heavily relient on Telerik's ASP.NET AJAX controls.

I've yet to have to opportunity to interview the person responsible for this request, so I'm unsure of the drivers for this, but I believe that as well as looking for a more structured solution (the original was developed in a very organic way) I believe that one of the goals is to also get a lot of the code running client-side and to use a structured form for the development there also.

So, My question is, is there a defined set of considerations for something like this? Or, if people do this kind of thing at all, do they just wing it?


问:
How do I alter my solution / project when the spec changes
I have a question about the best practice in this situation.

At one point, my small application allowed the client to upload a file to a server, and download a file from the server (it would also compress / decompress as well).

This was created in 1 solution which consisted of 4 projects:

FTP

CompressDecompress

UI

Tests

Now, the spec has changed and there will 2 end users, one who only wants to upload, the other who only wants to download and they should never have access to anything else (ie downloading people cannot upload and vice versa).

So, I have a few choices here. I could either

Keep it as 1 solution, and ask users to login, based upon the credentials will display a different UI

Alter my UI so it only shows tools to download, create a new solution which consists of just a UI project and reference my .dll accordingly.

Delete my UI, create 2 new solutions, each solution being created for either download or upload (and each solution probably only consisting of just 1 project, the UI) and again, referencing the .dll

Does any one have any suggestions? Would any guidelines have allowed me to have not gotten into this situation in the first place (or at least made me more aware of the potential disasters)?

答:
I am mildly surprised by the requirement that the uploading user is only allowed to upload. I can see a use-case for read-only access (download only), but much less for write-only access (upload only), unless that role is to be filled by an automated system.

With that in mind, I would weigh my options as follows

If both users are expected to be human, extend the UI with login functionality and provide either the upload or download functionality, depending on the user credentials. This keeps the project future-proof for the case that there will be another requirements change to support both up- and download again for one user.

If one of the users is expected to be a machine, add another project to the solution, providing an API that is tailored for machine-machine communication, parallel to the functionality you currently have in the UI. The unneeded functionality should be stripped from the UI.

Big scope-changes like this can usually not be foreseen during the initial development of a project, so there are no guidelines to prepare your codebase for them.

What you can prepare for are requirements that seem oddly restricting (like the write-only user you have now), and write your code in such a way that the requirement can change without forcing a complete rewrite of a project.


问:
What happens when using address before it's allocated?
The very simple piece of C++ code below is incorrect, it's easy to see why and tools like Valgrind will tell you. In running several C++ codes containing this kind of error, I noticed that each time, it ended up with a Segmentation fault at the line which tries to use the address.

So my question is: is it safe to claim that trying to use an address before it's allocated will inevitably lead to a Segmentation violation at the corresponding line?

class ClassType
{
  public:int data_;
};

....
// Using address before it's allocated
ClassType * ClassType_ptr;
int x = ClassType_ptr->data_;
```

答:
No, absolutely not. If that were what invariably happens, we could use that to our advantage and specify it in the standard; known behaviour, even if it is a crash, is virtually always better than unknown behaviour.

But instead, the system response depends on details of the implementation, of the previous actions of the program, on the state of the runtime etc. in an unpredictable way. On modern operating systems referencing an address that doesn't belong to you may usually trigger a segmentation violation, but definitely not always. A segmentation violation might occur, but not until much later. Even worse, your program might appear to work but silently do the wrong thing. That's why the language standard has to take the worst possible option and declare that the behaviour is undefined.

(Note that goodness depends on your viewpoint. For the compiler implementor, undefined behaviour is good because it means that whatever you do is, by definition, right. For the application programmer it is bad, because it leads to application errors, and even to the particularly insidious kind of errors where things sometimes work and then fail spectacularly at the least opportune moment.)


答:
The machine and OS I first did some C++ programming on didn't even have seg faults because it didn't have any memory protection.

If I recall correctly, on that platform, your code snippet would have ClassType_ptr being 0 initially, and dereferencing it would (without error) return the first four bytes of RAM as an integer. Not what you wanted, surely, but no crash, no error.

That's why, as Kilian Foth said in the above answer, the behaviour is undefined.

Title: What happens when using address before it's allocated?

Body:
The very simple piece of C++ code below is incorrect, it's easy to see why and tools like Valgrind will tell you. In running several C++ codes containing this kind of error, I noticed that each time, it ended up with a Segmentation fault at the line which tries to use the address.

So my question is: is it safe to claim that trying to use an address before it's allocated will inevitably lead to a Segmentation violation at the corresponding line?

class ClassType
{
  public:int data_;
};

....
// Using address before it's allocated
ClassType * ClassType_ptr;
int x = ClassType_ptr->data_;
```


问:
Is is acceptable to create mediocre code now in preparation for new language features?
I'll be specific: Java 8 is promised to bring lambda expressions as well as method and constructor references among other things. As a Java developer I'm super psyched about that.

In my day to day programming I see more and more opportunities where using these features would greatly simplify code that would otherwise be very verbose and tedious. In lieu of method and constructor references I started using more and more reflection and plan to migrate those code paths to Java 8 as soon as possible. I use special comments (like the well known TODO comments: JAVA8) that can be used by the IDE or grepped easily in order to find the relevant places. I also test all those cases extensively to make sure they work.

But still I have to wonder whether it's good to do it like that. Is it acceptable to produce a little more brittle code now that will eventually become robust again? GA for Java 8 is September 2013 so it's not too far in the future (provided the release date doesn't slip).

A kinda general example would be something like this: I want to create some container objects and fill them with data from a database. If I were to use the standard Java approach, it could look like this:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, new FooInitializer());
  }

  public Container getContainer(Class cls) {
    return INITIALIZERS.get(cls).create();
  }

  interface ContainerInitializer {
    Container create();
  }

  class FooInitializer implements ContainerInitializer {
    Container create() {
      return new Container(database.getFoo());
    }
  }
}
```

The reflective code is

```
class ContainerService {
  private Database database;
  private final Map, String> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, "getFoo");
  }

  public Container getContainer(Class cls) {
    Method m = Database.class.getMethod(INITIALIZERS.get(cls));
    return new Container(m.invoke(database));
  }
}
```

Note how all the intermediate interfaces and classes fall away.

The Java 8 variant is something along the following lines:

```
class ContainerService {
  private Database database;
  private final Map, ContainerInitializer> INITIALIZERS = new HashMap();

  {
    INITIALIZERS.put(Foo.class, database::getFoo);
  }

  public Container getContainer(Class cls) {
    return new Container(INITIALIZER.get(cls).create());
  }

  private interface ContainerInitializer {
    Container create();
  }
}
```

This is slightly longer again but has type safety. Also it's trivial to get from the prepared code to the final code using method references.

Of course the example is a bit simple. Imagine having a lot of types the container could contain. In the first method, there would be an extra class for each of them. In the other two methods, only data has to be added. It keeps everything so much simpler.

答:
I share ZJR's opinion that you should stick to what is available today and develop for Java 6 or 7, if that is what you are using now: always use the tools that you have now for what they are, not for what they might be in the future.

I would add that if you really like anonymous functions and other functional-language idioms, you should consider switching to Scala, Clojure, or another language that already exists and fully supports such idioms, instead of waiting for Java to support a few of those idioms some time in the future. Otherwise, when you have your nice lambda expressions in Java 8, you might learn about pattern matching and start missing that (maybe you will get it with Java 10?) And then you will hear about currying or richer type-inference features, and will have to wait again.

So, I would stick to Java 6 for doing your object-oriented programming and switch to a language that truly supports functional programming if you wanted to do proper functional programming or a mix of object-oriented and functional programming. In other words, don't stick to Java if this language is not providing the combination of features that you are looking for.

And I also agree with "Don't fall for the chant of sirens.": I think Oracle is introducing some FP into Java (among other reasons) to keep selling Java to people who are not really interested in FP (otherwise they would be using a real FP language already) but do not want to be considered uncool for not knowing FP.

In my opinion, it is perfectly OK to stay out of this hype and continue to use purely object-oriented languages (like Java 6) if one feels comfortable with them. And if you write proper object-oriented code, it will not be "mediocre code".


答:
The main driver for doing anything using AJAX is to make the user experience better.

This is mainly done by having controls updated without page reloads.

This is a design choice.

I believe the Telerik AJAX controls can be used in MVC with a bit of extra work, but Telerik also has specific MVC controls.

So you could buy and use those (or similar from other vendors). These may not however map 1 to 1 with all the features you need.

Another option is a half way house, an MVC app can also contain .aspx pages, so you migrate your app slowly, with maybe some of the original pages brought in without changing them to MVC.


问:
What do you do with a heisenbug?
I've gotten a bug report from one of my users in a section of the software. The scenario is basically a databinding scenario where the user enters info, and that info is printed to pdf.

The problem is, that the functionality:

Is used frequently (about 40 times a week)

Hasn't been updated/modified in months

The area of code is relatively simple to walk through

The validation appears fine (ie, if the information wasn't filled out in the app, validation fires indicating it with a msgbox before the pdf is generated)

But this one user claims that in the past 2 weeks it's happened about 3 times out of 50 and I just can't reproduce it.

So what do you do in the case of a heisenbug?

答:
This is often caused by concurrent processes (not OS-level processes, just... general things that happen in your application: events, threads, input/output etc.) which both affect the rendering in some way. This leads to different behaviour depending on the order in which they happen, and debugging and breaking often interferes with that.

One good strategy is to replace stepping through the debugger with more logging -  this takes much less time and therefore is much more likely to leave things as they are while still giving you more information.

Ultimately, though, nothing beats understanding what the system actually does. Is there one component, and one only, which should be responsible for maintaining the state of the UI? (Usually there should.) If so, why is it getting inconsistent commands in the first place? Obviously, logging can often help answering these questions as well.

Title: What do you do with a heisenbug?


问:
What standard superseded 830-1998?
I have been looking into how to document software projects more formally, and I have learned about IEEE 830-1998:  Recommended Practice for Software Requirements Specifications.  However, as you can see from that link, it has been superseded.

I know that 830-1998, and probably even 830-1993, are probably just fine for use. However, if nothing else, I would like to know what standard has superseded it. In this case it may not matter, but if other standards are superseded for more technical things, I think it would be a good idea to link somewhere what standard superseded another (if it is not another one in the same line (830, in this case)).

It is worth mentioning that:

The most recent standard when searching for "Software Requirements Specifications" or "Software Requirements" on the IEEE Standards Association website is 830-1993,

The 2004 (current) version of SWEBOK references 830-1993 (paragraph 2.5),

The document's Wikipedia article doesn't mention that the standard was superseded.

TLDR:  How do you find what standard superseded another, and which one took 830-1998's place?

答:
I found this in the IEEE site:
http://standards.ieee.org/findstds/standard/29148-2011.html

The 29148:2011 standard seens to replace the IEEE 830:1998.

This standard replaces IEEE 830-1998, IEEE 1233-1998, IEEE 1362-1998.

ISO/IEC/IEEE 29148:2011 contains provisions for the processes and products related to the engineering of requirements for systems and software products and services throughout the life cycle.

It defines the construct of a good requirement, provides attributes and characteristics of requirements, and discusses the iterative and recursive application of requirements processes throughout the life cycle.

Title: What standard superseded 830-1998?


问:
Is this Observer variant an improvement?
In a C++ code base I've been working on, they have a bunch of instances of the observer pattern, but it's a little different from the classical pattern.  In the classic, the Observer is a specific interface with specific method(s) that are called when the Observable changes or has new data.

```<code>Observable                       Observer
register( Observer* )            update( data1, data2 ... )
</code>```

In our code base, we use a template class that takes the number and type of arguments to the update() method as parameters, and allows you to specify any pointer-to-method as the recipient of the data.

```<code>Observable
register( Functor<data1, data2> )
</code>```

Is this an improvement over the original pattern?  Here's what I think are the pros of each approach:

Classic:

clarity - the interface marks which classes are recipients of observable data

less code - the boiler plate and ugly template syntax to create the functor are somewhat onerous

Variant:

flexibility - I can make any object in my system receive the update (if it has the right method signature) without having to change the original object

As a another option, do I have it all wrong that this is the Observer pattern in practice?

答:
Just to check, you do know that your Functor is just std::function, right?

Secondly, it absolutely is better. You can register lambdas, function objects, etc, so it's far more flexible than requiring derivation, and you don't have to define ten billion interfaces, all of which are dupes of each other.


答:
Your idea was already invented 10 years ago by Herb Sutter. See this article: http://www.drdobbs.com/cpp/generalizing-observer/184403873, it contains a full explanation.

So the answer is

yes, it is an improvement over the original GOF variant of the pattern

no, it is not better than every other known implementation of the Observer pattern

Also note that what you suggested here is the "standard observer implementation" in functional languages or languages with functional elements where events/event sinks are typically implemented in a comparable way (for example, in C# using delegates).

Title: Is this Observer variant an improvement?

Body:
In a C++ code base I've been working on, they have a bunch of instances of the observer pattern, but it's a little different from the classical pattern.  In the classic, the Observer is a specific interface with specific method(s) that are called when the Observable changes or has new data.

```<code>Observable                       Observer
register( Observer* )            update( data1, data2 ... )
</code>```

In our code base, we use a template class that takes the number and type of arguments to the update() method as parameters, and allows you to specify any pointer-to-method as the recipient of the data.

```<code>Observable
register( Functor<data1, data2> )
</code>```

Is this an improvement over the original pattern?  Here's what I think are the pros of each approach:

Classic:

clarity - the interface marks which classes are recipients of observable data

less code - the boiler plate and ugly template syntax to create the functor are somewhat onerous

Variant:

flexibility - I can make any object in my system receive the update (if it has the right method signature) without having to change the original object

As a another option, do I have it all wrong that this is the Observer pattern in practice?


问:
Is it fair to ask a team to start using CoffeeScript?
I started my new job as a JS developer in November and starting implementing Backbone pretty soon after. This was a big enough learning curve for the team (me included), however I'm thinking about looking at CoffeeScript, which I'm guessing would require everyone on the team to know it? Is that too big of an ask, just to make me slightly more productive?</p>

答:
When working with good teams it is totally fair to introduce technologies to the team as a whole with a bit of a "Lunch and Learn" or some other format where you can go over the good and bad. Then one must let the team decide if this is a proper thing to use or not. It never works well to force a team to adopt a technology, doubly so when they are not ready for it.

If you are the team lead, or senior developer, or in any kind of leadership role, this is much more important. It can change how your team views your leadership abilities. If you introduce CoffeeScript as something that might be very useful, and demonstrate why and you can answer any questions they have and most importantly be ready to mentor and work with them then go for it.

Worst thing you can do is say, "Here is CoffeeScript. We are going to use it. It is very powerful and it will make your life easier here." and then not explain to them why, or how or even let them take the time to come to that conclusion themselves.


问:
Writing Clean, Elegant Procedural Code (BASIC): Is There Such a Thing?
I learned to code in OO languages. I've always been interested in design patterns, clean code, etc., etc. - you know the type.

Now at work I'm using a BASIC dialect. Given modern programming values, should we try to carry over these same principles to new procedural code?

I'm pondering the following issues, and I wondering if I'm on the right lines.

Variable Names

Variables are not strongly typed (nightmare!), they're given short names and written in ALL CAPS (why?!) - basically I find them hard to read and they could be anything. Once upon a time, I'm sure XCNT = 1 would have offered performance gains over int_EXISTINGCUSTOMERCOUNT = 1, but we're past that now - surely? I choose the verbose name here.

GOSUB

I want to break down long blocks of code down into multiple smaller blocks. Internally, GOSUB is used (over a FUNCTION) if the helper is not re-usable by other programs / functions. Given its ability to add / modify variables without the safety of scoping (as we know it in the OO world) GOSUB scares me.

This is typical:

```<code>GOSUB GET_BEST_CUSTOMER
IF RC = 0 THEN CRT CNAME
</code>```

But I would write:

```<code>rc_GETBESTCUSTOMER = 1 ; !Default exception
str_CUSTOMERNAME = ""
GOSUB GET_BEST_CUSTOMER ; !set rc_GETBESTCUSTOMER, populate str_CUSTOMERNAME
IF(rc_GETBESTCUSTOMER = 0) THEN
    CRT str_CUSTOMERNAME
END
</code>```

With the caveat that GET_BEST_CUSTOMER would only modify rc_GETBESTCUSTOMER and str_CUSTOMERNAME in 'global' scope.

There's more, but it's all along the same lines. Given the editor of choice (Notepad++), I'd say my coding style makes the code easier to read and understand - therefore easier to maintain. But I'm sure some BASIC die-hard would readily tell me I'm doing it all wrong.

答:
Variable Names

It wasn't about performance, it was about the system only being able to interpret values with a character length less than some value (8 in most cases).  Yes, verbose variable names are now allowed throughout, and use them to your heart's content, but if you get legacy code don't go changing variable names just because you don't like it (as per good coding practice should say anyway).  As well, all caps was used since some systems may not necessarily been on ascii standard, nor would some systems output the same print style to the screen, caps is an easy way to solve this since they should all be nearly similar.

GoSub

If you can't protect with scoping, protect with naming.  Each subroutine name should be short, that way if you do have to worry about "scoping" variables, you can append the subroutine name to the front or back of the variable, handle being descriptive about the subroutine in the comments, not the name.

Honestly, there's not a major paradigm shift from OOP to Procedural, yes there are some semantic issues, but subroutines are key in keeping your code maintainable and semi-modular, just like classes and methods are there for that same purpose in OOP.

And as always, stay away from GOTO (Dijkstra).


答: Introducing new skills and technologies should be a team decision. Your team needs to maintain your code if you are off sick, leave, or get hit by a bus. What does your team say? I have lost count of the number of projects that have been expensively damage to the point of needing a rewrite by some maverick introducing his favourite technology that no-one else understands, so make sure you are backed by consensus.</p>

Title: Is it fair to ask a team to start using CoffeeScript?

Body: I started my new job as a JS developer in November and starting implementing Backbone pretty soon after. This was a big enough learning curve for the team (me included), however I'm thinking about looking at CoffeeScript, which I'm guessing would require everyone on the team to know it? Is that too big of an ask, just to make me slightly more productive?</p>


答:
It's all about how it is done, and what your team is like.

A really smart technical team embraces change and doesn't care who introduces a piece of new technology so long as it helps of course.

The flip side is that is very often not the case.

Being the new guy can work against you ("who does this guy think he is?").

Not being a "lead" can work against you ("he can't tell us what to do!").


答:
I implemented a lot of variants of Observer pattern in C++ and one thing I learnt is that there is no generic way to do it unfortunately, a bit like trying to make a unique compiler.

It depends on what feature you need for the specific usage. One important feature that is or not required is disconnection.

Disconnecting an observer requires that we can identify the observer to disconnect. There are several ways to do this. Boost.Signals(2) do this by providing an object that is basically a handle to the connection and can be used to disconnect.

Your first example allow disconnection, as we can identify an observer by comparing pointers; your second example don't allow disconnection if Functor is std::function<> as it can't be compared (there is explicitly no == operator).

If your Functor<> can be compared correctly, then it is possible to disconnect. If it's not, then depending on the use case, it can be or not a problem.

Also, note that an Observer class can be more helpful in defining a set of messages that Must be all handled by the observer.

Really, it depends on the use case.


答:
I would suggest the Freedom Board from Freescale if you want to have a bunch of stuff on a single board.  The nice thing about this is, it can use C, C++, or Assembly, and it's completely self contained.  But, if you want to go the route of attaching it an Arduino board it's got the correct expansion headers to be able to do so.  It's also as cheap as the Arduino but has a more robust on-chip interface.

I've been using one as a standalone for the last few months and have really enjoyed it.  As well, I know my university is moving towards these for their EE 101 class to do an intro to hardware programming and all the soldering business of adding your own expansion headers. Also, these boards will be used by those EE 101 students to build a small vehicle to be used in competitions.  I figure, if it's good enough to be used as a teaching device and robust enough to be used in interscholastic competitions that it should be a reasonable board to get someone going with "mobile platform" programming and development.

Title: Cheap programmable, portable device


问:
Is there a cleaner way of caching data
We've started implementing some caching code in our MVC project.  We've derived from .Net's ObjectCache to store it in a SQL database.

What we do right now is in each method we want to cache we have code like this:

```<code>public StatusCounts GetCounts()
{
   var cache = new SqlCache<StatusCounts>("mykey");
   if(cache.HasCachedData())
      return cache.GetCachedData();

   var data = StatusRepository.GetCounts();

   cache.SetData(data, DateTime.Now.AddHours(2));
}
</code>```

As far as caching goes, it works. But my concern is it seems like now GetCounts has multiple responsibilities. It's no longer just calculating counts, it's getting them from a cache (if they exist) and saving them to a cache before returning.

Is there a cleaner way to do this?

答:
I would try to implement it using AOP. You could try Castle.Windsor's Interceptors or mechanism other IoC container have. That way you implement caching in one place only (Interceptor) and there is no sign of cache in your method.

http://docs.castleproject.org/Default.aspx?Page=Interceptors&NS=Windsor&AspxAutoDetectCookieSupport=1

Title: Is there a cleaner way of caching data


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答:
SQL

We used a naming convention for our database elements.

tblTableNames

viewViewName

spAdminProcedureName

spProcedureName

Oftimes we would create a widget for a customer and 3 months later we would resell that widget to another customer. Eventually naminging conflicts arose and we had to recode a widget.

For example:

Press Release Widget

tblContent

tblCategories

tblImages

Photo Gallery Widget

tblPhotos

tblCategories

If Customer-A already had the press release widget and now wanted the Photo Gallery widget we had a naming conflict with tblCategories. We couldn't just script the Photo Gallery elements and run them against Company-A's database. Argh!

So we we started appending a "widget" references to our SQL elements:

tblPG_Photos

tblPG_Categories

tblPR_Content

tblPR_Categories

tblPR_Images

spPG_Proc1

spPG_Proc2

spPG_Proc3

spPR_Proc1

spPR_Proc2

spPR_Proc3

This kept things nicely bundled and helped us be more profitable in the long run.


问:
what is the name of the model for the describing strategy between R&D and Professional Services
Is there a model that describes the different strategies that a company may use where the organisation is split into an engineering division and a professional services division?

This is the sort of model that is followed by companies like Microsoft, whereby Engineering (or R&D) produce the core software, and professional services can then help clients implement that software.

答:
I don't know that there is a specific name for that "model", but it's a reasonably common approach.  In addition to Microsoft (your example), AT&T*, HP, IBM, and quite a few others follow the same approach.  Even Dell and others are starting to embrace this approach.

The reasons should be fairly obvious.

R&D activities need to be run in a different manner than a typical profit / loss model.  R&D is explicitly for activities that may never pan out.  The corporation may push the R&D towards more likely to be practical / applicable efforts, but there isn't a guarantee that a product will result.  As an example, IBM used to heavily fund basic research.  As of the mid-2000's, researchers were encouraged to focus on aspects that were more likely to be applicable to market needs.

Services divisions are a typical example of a normal profit / loss model.  A Services division can measure utilization rates, profit margins (or losses), service backlogs, etc...   All of which are in alignment with selling a product (a service).

*I'm not certain about AT&T having a separate R&D division anymore, but they certainly used to.


答:
You can separate the cache initialization from returning the value, and implement the cache initialization in a generic way:

```<code>public StatusCounts GetCounts()
{
   var cache = GetInitializedCache<StatusCounts>("mykey",StatusRepository.GetCounts,2);
   return cache.GetCachedData();
}

private SqlCache<T> GetInitializedCache<T>(string key,Function<T> getData,double hours)
{
   var cache = new SqlCache<T>(key);
   if(!cache.HasCachedData())
   {
      T data = getData();
      cache.SetData(data, DateTime.Now.AddHours(hours));
   }
   return cache;
}
</code>```

That will separate the concerns of caching and calculating the values as well as giving you a reusable function. Of course, the method body of GetCounts is still aware of the caching mechanics, and if you want to avoid that too, @Peri's answer maybe the right approach (for the price of having to introduce a non-trivial third-party component).

Title: Is there a cleaner way of caching data

Body:
We've started implementing some caching code in our MVC project.  We've derived from .Net's ObjectCache to store it in a SQL database.

What we do right now is in each method we want to cache we have code like this:

```<code>public StatusCounts GetCounts()
{
   var cache = new SqlCache<StatusCounts>("mykey");
   if(cache.HasCachedData())
      return cache.GetCachedData();

   var data = StatusRepository.GetCounts();

   cache.SetData(data, DateTime.Now.AddHours(2));
}
</code>```

As far as caching goes, it works. But my concern is it seems like now GetCounts has multiple responsibilities. It's no longer just calculating counts, it's getting them from a cache (if they exist) and saving them to a cache before returning.

Is there a cleaner way to do this?

Body:
You can separate the cache initialization from returning the value, and implement the cache initialization in a generic way:

public StatusCounts GetCounts()
{
   var cache = GetInitializedCache<StatusCounts>("mykey",StatusRepository.GetCounts,2);
   return cache.GetCachedData();
}

private SqlCache<T> GetInitializedCache<T>(string key,Function<T> getData,double hours)
{
   var cache = new SqlCache<T>(key);
   if(!cache.HasCachedData())
   {
      T data = getData();
      cache.SetData(data, DateTime.Now.AddHours(hours));
   }
   return cache;
}

That will separate the concerns of caching and calculating the values as well as giving you a reusable function. Of course, the method body of GetCounts is still aware of the caching mechanics, and if you want to avoid that too, @Peri's answer maybe the right approach (for the price of having to introduce a non-trivial third-party component).