问:
Advantages and disadvantages to making common unit test scaffolding code
For the project my team and me are working on we often find that we need large pieces of scaffolding code. Creating domain objects with correct values, setting up mocks for repositories, dealing with the cache,... are all things that occur commonly throughout the tests. A lof of times we're working with the same basic objects that are central to our domain (person,...) so lots of tests create instances of these objects for other objects to work on. We have a lot of different solutions using the base domain so this kind of code is often spread across those solutions.

I've been thinking about creating common classes that do a lot of this scaffolding. This would allow us to request a fully instantiated person with everything set up (access via repository, caching...). This removes duplicate code from our individual unit tests but would also mean there is a large amount of code that probably does 'too much' per test (as it would set up a full object and not just the parts required).

Has anyone ever done this? Are there any insights, remarks, thoughts... you can offer that might validate or invalidate this approach?

答:
I can relate to this question.  On my team we've tried to do TDD before and it was the same story, too many tests required a lot of scaffolding/utility methods that we simply didn't have.  Because of time pressures and few other not so right decisions, we ended up with unit tests which were very long and reinvented things.  Over the course of a release, those unit tests became so convoluted and hard to maintain, we had to drop them.

I'm currently working with few other developers on reintroducing TDD back into the team, but instead of simply telling people, go write tests, we want to do it carefully this time and people have the right skills and the right tools.  Absence of the common support code is one thing we identified where we need to improve so that when others do start writing tests, all the code they write would be small and to the point.

I don't have as much experience in this area yet as I'd like, but few things I'd suggest based on work we did so far and some homework I've done:

Common code is a good thing. Doing same work 5 times makes no sense and under time pressures at least 4 of those times will be half-assed.

My plan is to build up common framework, then build up TDD leadership team consisting of 4-6 developers.  Have then write unit tests, learn the framework and provide feedback on it.  Then have these guys go out to the rest of the group and guide other people in producing maintainable unit tests that utilize the power of the framework.  Also have these guys gather feedback and bring it back into the framework.

For the examples you've provided with Person class, I'm actually investigating the use of mockpp or googlemock frameworks.  Leaning towards googlemock for now, but haven't tried either yet.  In either case, why write something that can be "borrowed"

Be careful about creating "god" fixtures that instantiate objects for all tests regardless if those tests actually need those objects.  This is what xUnit Test Patterns calls "General Fixture Pattern".  This could cause few problems such as a) each test taking too long to run due to excessive setup code and b) tests ending up having too many unnecessary dependencies.  In our framework each test class picks exactly which framework features it needs in order to execute, so no unnecessary baggage is included (in the future we might change it to each method picking independently).  I got some inspiration from Boost and Modern C++ Design and came up with a base template class that takes a mpl::vector of needed features and builds custom class hierarchy specifically for that test.  Some really nifty captain cruch decoder ring super crazy black magic template stuff :)


问:
Academic programming languages?
Back in the day, there were a lot of academic programming languages (okay, maybe not a lot, but it seems like there were more than today). I distinctly remember spending time in both high school and college learning languages like Basic, Ada, Pascal, Prolog, Haskell, Scheme, and Turing. While it's unfair to call all those languages solely academic, it's also unfair to say they are industrially equivalent to an enterprise language like Java (or even C or Smalltalk back in the day).

My question is, what academic languages are still in use (and still taught today)? It seems like there's a lot of Java schools, and a rising number of Python schools, and even some that teach languages like C as the first programming language - but what would be the modern equivalent to something like Pascal?

答:
Uuh, this is not a well worded topic :)

Although there is no doubt some languages are more used in industry than other, naming them is controversial, and depends heavily of what industry you're in. For example, C okey, Java okey (they're rather mainstream, and their influence is rarely questioned nowadays), but I've never (until I started following these forums) even heard of Smalltalk, less alone heard of anyone doing something with it. Actually, I still don't know of anyone doing anything with it...

That being said, I know of several small to mid size project in Basic, and several medium in Pascal (depends on one's classification of small/medium/large). Never heard of anything being done in Turing, neither in the academia nor in the industry.

I'm sure others will have similar experiences to share.

See my point? Everyone will have different views on this ... so putting together a list of used in industry and used in academia languages is really a non-grateful task.

As to the modern Pascal equivalent, if you're excluding Delphi I would go with Python. It hip, it's popular, it's everywhere and a lot of people swear everything can be done with it. Just like Pascal in the 80s :)

ContentLicense: CC BY-SA 3.0

Title: Academic programming languages?


问:
What should I learn in Java SE before proceeding to Java EE?
Currently, I've learned the following in Java SE:

Logical Operations

Loops

Inheritance

Polymorphism

Abstract Classes

Interface

I'm currently learning Strings, Characters and Regular Expressions. What are things that I should learn before proceeding to Java EE?

答:
You might already know this but they are one in the same except that Java EE is the enterprise version, meaning more advanced features such as servlets.

I would say learn everything in SE (core) java before going into the Enterprise Edition. Now it's not enough to learn something to know it, you should understand it as well.

For example: Why does Java have Multiple Inheritance in terms of implementing multiple interfaces rather than extending multiple abstract classes like C++?

OR

Why would you use and Abstract class over an interface and vice versa?

I'd say gather as much of an in-depth understanding to the core aspects of java before tackling the advanced topics. Also conquer data-structures, Object Orient Principles, Generics, Threading, annotations, and anything else that may envelop the basic understanding of java. Now of course you don't have to know all the intricacies of java just have somewhat of a basic understanding.

Scour forums and EXPERIMENT! Code non-stop until your fingers bleed. Lastly always ask questions to what you have learned!!!!

Any fool can know. The point is to understand.
  -Anonymous


问:
Software testing automation documentation
What document types could be used when describing software testing automation (on any phase, automation planning, test design, implementation, reporting)? Is there any standard types of documents?
If someone could provide any examples and templates for different types of documents?
What is the difference between manual testing documentation and automated?</p>

答:
The answer greatly depends on what the software does, how it is designed, and even the industry the software will be used in. Some industries have very extensive regulatory requirements for test documentation & validation, for example FDA CFR 21 Part 11in the Pharma and Biotech industries.

Also, consider that even if your organization would religiously follow all the relevant IEEE standards for testing documentation, such as:

IEEE 829: software test documentation

IEEE 1008: unit testing

IEEE 1012: software verification and validation

IEEE 1028: software inspections

IEEE 1044: classification of software anomalies

there is a plethora of directly and indirectly related documents and standards you should also define and use, like:

IEEE 830: system requirements specifications

IEEE 730: software quality assurance plans

IEEE 1061: software quality metrics and methodology

IEEE 12207: software life cycle processes and life cycle data

If all of those IE3 standards look insurmountable - especially for smaller organizations and teams - have a look at the Software Engineering Body of Knowledge which is less "scientific" and more concise.

Finally, to some extent, using ALM tools that keep electronic records of tests in stead of formal documents is a perfectly valid alternative as long as you have procedures that define a standardized use.


答:
There seems to be a constant debate on the ups and downs of even teaching something like an academic language. I've heard (especially more recently) lots of people who are completely ok with teaching C(++) and Java only. Personally, having gotten the benefit of being taught various different languages and paradigms I do believe this is too shortsighted though.

With that said, I do believe it is really hard und probably unjustified to classify a programming language as academic, hence, implying it is not used for practical purposes. There are a few such languages (f.ex., Whitespace and other such esoteric ones), but you will see that you will have to reason with every other person on which language the two of you consider academic - and the third person will disagree.

Of the academic languages you named, I have seen half of them being used in the industry for commercial products (Ada, Pascal, Prolog, Haskell). And I even see much less known languages being used in companies. Certainly, only few companies dare to venture that path.

Closing in on your actual question: which languages are still in use and being taught today?

I'd say most of them. Personally, my alma mater has just recently upgraded their courses to a new set of courses. Interestingly enough, these courses now contain even more courses that deal with languages other than Java or C. For example, Prolog and Haskell are still being taught to new students.

Even if the likelihood of applying that knowledge in an industrial setting is low, the thought processes you develop when learning about logic and functional programming will give you an edge over pure Java-schoolers for decades to come.

Title: Academic programming languages?

Body:
Back in the day, there were a lot of academic programming languages (okay, maybe not a lot, but it seems like there were more than today). I distinctly remember spending time in both high school and college learning languages like Basic, Ada, Pascal, Prolog, Haskell, Scheme, and Turing. While it's unfair to call all those languages solely academic, it's also unfair to say they are industrially equivalent to an enterprise language like Java (or even C or Smalltalk back in the day).

My question is, what academic languages are still in use (and still taught today)? It seems like there's a lot of Java schools, and a rising number of Python schools, and even some that teach languages like C as the first programming language - but what would be the modern equivalent to something like Pascal?


问:
Comment before or after the relevant code
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.

答:
Comments above is best.

if you have to include comments and your code is not self-explanatory, then I would rather not be confused by a block of code, then see "ahh, that's what it was supposed to do".

Code can (and should) be "self documenting", but if you have to read and understand every line of code to understand how a method works. If a summary/ comment found in the last of method then it will be lot of coding time is spent searching for the chunk of code that we wish to edit. By using a summary comment on each block, I can quickly zero in on the block that is relevant to my task.

When i have goggled about this topic, i found that most computer-readable documentation systems (Doc XML, Doxygen, Java doc etc) expect the comment to come before the code it relates to - it's better to remain compatible with that standard.

I am also agree with the SO thread - Should we be adding comments after code blocks, rather than before? ..

I'd also rather know up front...


答:
"Any problem in computer science can be solved with one additional layer of indirection. But that usually will create another problem." – David Wheeler

(disclaimer: I'm part of JDT's team, so I have some more inner knowledge of the problem presented here)

The essential problem here is that the objects in the framework themselves expect a database connection, as its loosely based on the CSLA framework by Rockford Lhotka.  This makes mocking them almost impossible (as you'd have to change the framework to support this) and also violates the black-box principle a unit test should have.

Your proposed solution, while not a bad idea in itself, will not only require a LOT of work to get to a stable solution, but will also add yet another layer of classes that needs to maintained and extended, adding even more complexity to an already complex situation.

While I agree that you should always look for the best solution, in a real-world situation such as this, being practical has its values as well.

And practicality suggests the following option:

Use a database.

Yes, I know technically speaking its not a "real" unit test anymore then, but strictly speaking the moment you cross a class boundary in your test, its not a real unit test anymore either. What we need to ask ourselves here is, do we want 'pure' unit tests that will require loads of scaffolding and glue code, or do we want testable code?

You might as well make use of the fact that the framework used encapsulates all database access for you, and run your tests against a clean sandbox database. If you then run each test in its own transaction, and rollback at the end of each 'logical' set of tests, you shouldn't have any problems of interdependency or test order.

Don't try and out-database a database.

OwnerDisplayName: JDT

Title: Advantages and disadvantages to making common unit test scaffolding code

Body:
For the project my team and me are working on we often find that we need large pieces of scaffolding code. Creating domain objects with correct values, setting up mocks for repositories, dealing with the cache,... are all things that occur commonly throughout the tests. A lof of times we're working with the same basic objects that are central to our domain (person,...) so lots of tests create instances of these objects for other objects to work on. We have a lot of different solutions using the base domain so this kind of code is often spread across those solutions.

I've been thinking about creating common classes that do a lot of this scaffolding. This would allow us to request a fully instantiated person with everything set up (access via repository, caching...). This removes duplicate code from our individual unit tests but would also mean there is a large amount of code that probably does 'too much' per test (as it would set up a full object and not just the parts required).

Has anyone ever done this? Are there any insights, remarks, thoughts... you can offer that might validate or invalidate this approach?


答:
I often convert comments (mine as well as written by others) into trace level log statements. This typically makes it much easier to understand where to place it.

```<code>    // Return an empty list if we failed to retrieve anything
    // I convert above to:
    logger.trace("Return an empty list if we failed to retrieve anything");
</code>```

An additional advantage is that when going gets tough I can turn on log tracing and get more detailed execution log.

Title: Comment before or after the relevant code

Body:
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.

Body:
I often convert comments (mine as well as written by others) into trace level log statements. This typically makes it much easier to understand where to place it.

    // Return an empty list if we failed to retrieve anything
    // I convert above to:
    logger.trace("Return an empty list if we failed to retrieve anything");

An additional advantage is that when going gets tough I can turn on log tracing and get more detailed execution log.


问:
Development of a bot/web crawler detection system
I am trying to build a system for my company which wants to check for unusual/abusive pattern of users (mainly web scrapers).

Currently the logic I have implemented parses the http access logs and takes into account the following parameters to calculate the potential of a user being a scraper or bot:

It checks v/s HTTP 'POST/GET' requests ratio for each IP

It calculates the ratio of unique URLs and total number of hits (sparsity) by each IP

Based on the above two parameters, we try to block any IP showing unusual behaviour, but these two parameters alone have not been sufficient for bot detection. Thus I would like to know:

Are there any other parameters which can be included to improve the detection?

I found a paper published in ACM library which follows the Bayesian approach to detect a crawler. Has anyone used this? How effective is this?

Stack Overflow and other high traffic sites have such kind of systems deployed, what logic do they follow to keep unwanted spammers/crawlers away in real time?

答: Just embed some invisible links in your html.  Anyone that follows one is a robot or scraper.</p>


问:
Does Agile force developers to spend more time actually working?
Looking at common Agile practices it seems to me that they (intentionally or unintentionally?)  force developers to spend more time actually working as opposed to reading blogs/articles, chatting, coffee breaks and just plain procrastinating.

In particular:

1) Pair programming - the biggest work-forcer, just because it is inconvenient to do all that procrastination when there are two of you sitting together.

2) Short stories - when you have a HUGE chunk of work that must be done in e.g. a month, it is pretty common to slack off in the first three weeks and switch to OMG DEADLINE mode for the last one.

And with the little chunks (that must be done in a day or less) it is exact opposite - you feel that time is tight, there is no space for maneuvering, and you will be held accountable for the task pretty soon, so you start working immediately.

3) Team communication and cohesion - when you underperform in a slow, distanced and silent environment it may feel ok, but when at the end of the day at Scrum meeting everyone boasts what they have accomplished and you have nothing to say you may actually feel ashamed.

4) Testing and feedback - again, it prevents you from keeping tasks "99% ready" (when it's actually around 20%) until the deadline suddenly happens.

Do you feel that under Agile you work more than under "conventional" methodologies? Is this pressure compensated by the more comfortable environment and by the feeling of actually getting right things done quickly?

答:
Do you feel that under Agile you work more than under "conventional" methodologies?

If you mean do I feel more productive under Agile, I'd say it depends.

I usually think of it in terms of Ferrari (as conventional) vs Landrover (as Scrum). When driving on a highway Ferrari beats the hell out of Landrover.

It's the off-road when one needs jeep not sports car - I mean if your requirements are irregular and/or if the team work and management experience are not that good, you'll have to choose Scrum - simply because trying go conventional will get you stuck - like Ferrari will stuck off-road.

As for "work more", well I think one expecting stuff like that likely underestimates programmer's IQ and their ability to adapt to various forms of management dementia.

So far, I participated in two Scrum teams making quite different projects in different companies. In both teams I did not notice any change in my habits compared to eg waterfall / iterative.

 I would be proud to claim that this is because I am so special and invincible but frankly, I've seen habits of all other guys in team being invincible, too.


问:
Generating presentation elements with Javascript vs PHP
What are the pros and cons of generating dynamic pages with javascript vs doing it in PHP?

As an example, I want to display certain records from some database in a table and I'm considering the following approaches:

Use Javascript to get some response in JSON from some PHP page, then dynamically build the table in Javascript.

Write some PHP in the page which will make the query and iterate through the result set echoing the table markup.

What are the pros and cons of each approach?

答:
All things being equal, go with the simplest option.

Option 1 requires that you export your PHP data to JSON, load it through an AJAX call, then iterate and render it with JavaScript.

Option 2 only requires that you iterate over a PHP array, no JavaScript necessary.

The beauty of ajax is that you can load the data asynchronously without reloading the page, the downside is that it's more work for you and won't function properly in every browser (or for any user with JavaScript deliberately disabled).


问:
Choosing language to write general library in
I'm about to start writing a library to support machine learning algorithms (decision trees, ANNs, Bayes nets, etc.), and I'm planning on making this a very general library. By this, I mean I want to be able to plug this module into as many languages as possible.

To clarify, here's why I've started writing it in C++ (Windows headers):

I know I can import C++ libraries into C#, and I've heard you can import C++ into Python. So, obviously, the library can be used in 3 languages, possibly 4 if I don't use system-specific headers.

Is there a language where I can cover a wider spread, weighted by popularity of languages? (For example, C# and C++ have pretty high weight to me because I use both frequently, Python less so.)

答:
If you are careful, you can write a quite general library with several bindings to other languages. For example both GTK (a graphical toolkit, coded in C, LGPL licensed) and Parma Polyhedra Library (a library handling numerical inegalities and abstractions, coded in C++, GPL licensed) have interfaces to several languages. Be sure to learn how to bind code to several languages & implementations (Ocaml, C++, Python, Haskell, Java, Lua, ...). Learn about memory management and garbage collection techniques.

I also suggest that you make your library free software, it is IMHO the best (and perhaps the only) way to make it widely used.

I strongly suggest that you make your library working on several platforms (from the beginning), like Windows, Linux, MacOSX. Don't make it Windows only!

Study the competitor's libraries. There already exist several machine learning libraries.

So the language to code your library is not the most important factor. And you could also make it a server, with published protocol to access it.

Perhaps chosing the language you know well is better. Otherwise, I might recommend Ocaml, C, C++, Java, ...

hints for C++

If coding in C++ consider using a recent C++11 compliant compiler and perhaps some cross-platform library framework like QtCore or Poco


答:
Ocaml, Haskell, Scala, Clojure are perhaps "academic" languages, but there are several companies using them extensively.

And learning widely different language make you think differently, even when programming in a mainstream language. So learning Ocaml or Scheme will change the way you think and code in C++ or Java.

The SICP is an excellent book & course, based upon Scheme.

Title: Academic programming languages?


问:
Silverlight UI and PRISM - how to properly break down components?
This is how my solution looks like right now. And it get's to the point where my Controls need reference to Model. It get's real tough to keep Infrastructure, Constants, Controls and Model separated.

For download size and modularity MAIN and Modules (there is many) will stay separate. But those core libraries seem to be referenced by all modules and MAIN. I don't see a point in keeping them in separate projects. I'm sure all of you had this same issue.

So, I wonder if I should keep trying and keep them separate/loosely coupled (hard to do now without circular references) or it is OK to merge them into one Infrastructure project? My Model has lot's of metadata and this metadate needed in controls and other places. Thats where it get's tight.

答:
You must keep Controls from referencing Model, looks like you are trying to cut some corners and your classes and structures used by UI controls start to leak in ViewModels, and even further the Model.

Think of DataGridRow, you do not use collection of DataGridRows in ViewModel, you use collection of Domain objects.

Data binding and Converters, are the tools to help you keep things separate, when designing your UI controls try to think abstract, imagine that you do not know with what kind of data they will work, try to think on user experience (behavior) they should provide.


答: Examine the frequency at which requests are coming in, and if it is exceedingly high, throttle the requests. This way, you are not blocking anyone, and yet nobody can consume too much bandwidth.</p>

Title: Development of a bot/web crawler detection system

Body:
I am trying to build a system for my company which wants to check for unusual/abusive pattern of users (mainly web scrapers).

Currently the logic I have implemented parses the http access logs and takes into account the following parameters to calculate the potential of a user being a scraper or bot:

It checks v/s HTTP 'POST/GET' requests ratio for each IP

It calculates the ratio of unique URLs and total number of hits (sparsity) by each IP

Based on the above two parameters, we try to block any IP showing unusual behaviour, but these two parameters alone have not been sufficient for bot detection. Thus I would like to know:

Are there any other parameters which can be included to improve the detection?

I found a paper published in ACM library which follows the Bayesian approach to detect a crawler. Has anyone used this? How effective is this?

Stack Overflow and other high traffic sites have such kind of systems deployed, what logic do they follow to keep unwanted spammers/crawlers away in real time?


问:
A free game-development language?
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.

答:
Sounds like a typical case for modding. Many games are very flexible and extendable, from the good old Quake I (with its QuakeC language) to TES IV Oblivion, or dozens of titles that can be extended with Lua.

Another option is Second Life - it is a very flexible world where one can build games, simulations, demos, whatever else with a nice and clean scripting language.

Title: A free game-development language?


答:
Bedwyr Humphreys is talking about a Builder solution which I've used a couple of times, and it really works fine. Almost no code duplication and constructing domain objects in a nice clean manner.

```<code>User user = UserBuilder.anAdminUser().withEmail("test@example.com").build();
</code>```

I'm not such a fan of code generation (scaffolding, codesmith, lblgen,..). It only helps you to write duplicate code much faster, not really maintenance friendly. If a framework is causing you to write lots of duplicate (test)code, maybe you need to find a way to move the code base away from the framework.

If you keep writing repository acces code, you might be able to solve this with a generic base repository and have a generic base testclass that your unit tests inherit from.

To avoid code duplication AOP can also help for things like logging, caching,...

Body:
Bedwyr Humphreys is talking about a Builder solution which I've used a couple of times, and it really works fine. Almost no code duplication and constructing domain objects in a nice clean manner.

User user = UserBuilder.anAdminUser().withEmail("test@example.com").build();

I'm not such a fan of code generation (scaffolding, codesmith, lblgen,..). It only helps you to write duplicate code much faster, not really maintenance friendly. If a framework is causing you to write lots of duplicate (test)code, maybe you need to find a way to move the code base away from the framework.

If you keep writing repository acces code, you might be able to solve this with a generic base repository and have a generic base testclass that your unit tests inherit from.

To avoid code duplication AOP can also help for things like logging, caching,...


问:
How Much Logic in Getters
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?

答:
The way work tells you to do things is lame.

As a rule of thumb, the way I do things is as follows: if getting the stuff is computationally cheap, (or if most chances are that it will be found in the cache,) then your style of getStuff() is fine. If getting the stuff is known to be computationally expensive, so expensive that advertising its expensiveness is necessary at the interface, then I would not call it getStuff(), I would call it calculateStuff() or something like that, so as to indicate that there will be some work to do.

In either case, the way work tells you to do things is lame, because getStuff() will blow up if loadStuff() has not been called in advance, so they essentially want you to complicate your interface by introducing order-of-operations complexity to it. Order-of-operations is pretty much about the worst kind of complexity that I can think of.

Title: How Much Logic in Getters


问:
Tool for large scale graph analysis
What are the best tools / frameworks / libraries available to implement and run algorithms on graphs?

In particular I need a tool that can load a set of nodes, edges and values assigned to these edges and then allows me to perform operations on them.

I already found R but I'm wondering if there is a more "programmer friendly" tool available?

答:
Depending on what kind of operations you're talking about, I used yFiles a few years ago and found it to be extremely powerful for graph visualisation - as well as having best-of-breed algorithms for things like automatic layout, shortest path analysis etc

The main library is Java but there are also .NET and Flex ports.

Could be worth looking at :)

Title: Tool for large scale graph analysis


答: I haven't played with it in a year or two, but using C# with XNA could be a good place to start. From what I remember, getting started with it is quite easy. Though that link is probably more for you than him.</p>

Title: A free game-development language?

Body:
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.


问:
How common are "bandage" fixes?
Imagine the following scenario:

You've detected that your (or someone else's) program has a bug - a function produces the wrong result when given a particular input. You examine the code and can't find anything wrong: it just seem to bog out when given this input.

You can now do one of two things: you either examine the code further until you've found the actual cause; or you slap on a bandage by adding an if statement checking if the input is this particular input - if it is, return the expected value.

To me, applying the bandage would be completely unacceptable. If the code is behaving unexpectingly on this input, what other input that you've missed will it react strangely to? It just doesn't seem like a fix at all - you're just shoveling the problem under the rug.

As I wouldn't even consider doing this, I'm surprised at how often the professors and books keep reminding us about how applying "bandage" fixes is not a good idea. So this makes me wonder: just how common are these kinds of "fixes"?

答: Depends a lot on the age of the code base I think. On old code I think it is very common, rewriting that 20 year old COBOL routine is not fun. Even on moderately new code that is in production it is still pretty common.</p>

ContentLicense: CC BY-SA 2.5

Title: How common are "bandage" fixes?


答:
Just do it as @MikeNakis said... If you just get the stuff then it's fine... If you do something else create a new function that does the job and make it public.

If your property/function is doing only what it's name says then there isn't much room for complication left. Cohesion is key IMO

Title: How Much Logic in Getters

Body:
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?


答:
Try Greenfoot,

Image http://www.greenfoot.org/images/screenshot.png?1310995619

Its java based and there are all these totorials for using it on Youtube.

greenfoot provides a good top-down approach meant for a beginner.

see this stackoverflow answer, the thing i noted there was "Children, in fact, are the fastest learners and they do so by pattern-matching, extrapolation, interpolation, etc.."

so after using java in greenfoot for a while later concepts will be easier to understand just because it feels familiar.

Title: A free game-development language?


答:
I'm currently an avid user of Game Maker. - While the full version isn't free ($40) the free version is enough to taste the basics of game design. It has enough "content" for somebody new to stay busy for a few years. If I would have to place it somewhere, I'd place it somewhere between modding & languages such as python.

It has several methods of writing. You can use "drag and drop icons", and a much more advanced "scripting language" (GML). I never understand why people wish to "write code" so much - I see drag and drop just as a way of visualizing code.

Another advantage of gamemaker -and the reason that after learning other languages, and 10 years of experience I stick to gamemaker- is that it helps organizing a game: It has several resources, an event system etc etc.

It's not the ideal tool to create the next world of warcraft, however to impress others it's more important to create SOMETHING.

I can't really recommend on other choices - as I personally am happy with gamemaker and nowadays take more interest into learning general purpose languages.

Title: A free game-development language?


答:
Logic in getters is perfectly fine.

But getting data from a database is a whole lot more than "logic". It involves a series of very expensive operations where lots of things can go wrong, and in a non-deterministic way. I'd hesitate do that implicitly in a getter.

On the other hand, most ORMs support lazy loading of collections, which is basically exactly what you're doing.

Title: How Much Logic in Getters


答: Not a programming language explicitly for gaming, but very cool graphical effects can be done using rather little code with processing. Plus, it's free and relatively easy to learn. IMHO an ideal language to learn the basics of programming, especially since the tutorials teach many of the basic concepts like variables, arrays, math operations etc.</p>

Title: A free game-development language?


问:
What is the recommended way to separate current development from maintenance development in version control software?
I have some software application managed using Git. I just released a new version 2.x which I plan to maintain on the long term (bug fixes mostly). In the meantime, I would like to start working on version 3.x. What is the recommended way to manage this? Should I create a branch for version 2.x and have the 3.x development on the master? or the other way?</p>

答:
My principle is that the more short term the branch is, the deeper it should be in the branch structure and the more specific its name will be.  The longer term the branch is, shallower it will be in the branch structure and more generic its name will be.

So you keep your master for the longer term (3.X) version and you keep naming this branch with a generic name (master, trunk, devel, ...) and not a specific one (release code name or even worse release numbers which are too much dependend in practice on late marketting decision)

It does not matter so much in a system like git which has a flat name space for branches and where branches are equivalent.  It matters more with a system like clearcase which has a hierarchical namespace for branches (the full name of the V4 branch end up beeing main/v1/v2/v3/v4...)


问:
How can I convince management to deal with technical debt?
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?

答:
After this explanation of technical debt, your management should be convinced to pay it off :

Imagine that you have a very dirty kitchen full of crap. Before preparing a meal, you have to first spend one hour cleaning. And it is like that every time you want to eat. Also, when preparing a meal, you have to be extra careful, to make sure the crap does not fall in your meal.

The kitchen is your code, meal is your product, and eating is selling your product.

If they can afford to wait longer for a change to be implemented, without a safe-net of unit tests, then there is something wrong in your company.


答:
A very interesting way of doing things was described here: A successful Git branching model

I found it very intriguing, but have yet to actually use it.

Very well, as requested a (very) short summation of what the article says:

The Master branch only every represents finished milestones (i.e. Version 1.0, 1.1, 1.2 etc.)

Development is done in it's own branch (conveniently named "develop", who'd have thought?). The develop branch is merged back into the the Master branch, whenever a feature complete version is done.

Branching off from development are feature branches. These represent single features for the next (or any future) release. They merge back with the develop branch.

Another branch coming from development is the "release" branch. This is a branch that represents an almost complete release version where only minor details have to be cleaned up. It merges with the development branch and ultimately with the Master branch

"Hotfix" branches branch of from the master branch if you find a severe bug in one of your releases (i.e. "If the use enters the konami code our program will reformat the main harddrive..."). It branches of from the buggy release and, when the fix is finished is merged back into the master branch AND the devlopment branch.

That's the short of it, but trust me, that the article describes it in way more detail, and with the helpfull visualisation graphic it is much easier to understand.

Title: What is the recommended way to separate current development from maintenance development in version control software?

Body: I have some software application managed using Git. I just released a new version 2.x which I plan to maintain on the long term (bug fixes mostly). In the meantime, I would like to start working on version 3.x. What is the recommended way to manage this? Should I create a branch for version 2.x and have the 3.x development on the master? or the other way?</p>


问:
Version control programs for XML-files - merge/diff tool
My programming environment / language (gamemaker) gives the source files as "XML-files". Each resource has its own XML file. Where the properties (code is a property) are stored inside xml tags.

Is there a source control which can handle these? With subversion collisions don't seem to be handled correctly: when a collision happens, subversion breaks the XML structure. Which in turn breaks Gamemaker when updating.

EDIT (editing here as comments don't seem to handle newlines :P), an example of a source file that got "destroyed" by subversion:

```<code><object>
  <spriteName>sprBall</spriteName>
  <solid>0</solid>
  <visible>-1</visible>
  <depth>0</depth>
  <persistent>0</persistent>
<<<<<<< .mine
  <parentName>self</parentName>
=======
  <parentName>objExplosion</parentName>
>>>>>>> .r16
  <maskName><undefined></maskName>
  <events/>
</object>
</code>```

EDIT2: because of lack of experience with these tools, I asked the wrong question. So here a better wording:

In the example above an xml-file-reader will crash when trying to read the file. However manually resolving the conflict is "hard". (And in extreme cases impossible). "" doesn't say anything in itself. - As the first question becomes "parent name of what?"- An object? - which object? In this case one can see it quickly. However if the xml file reaches 100+ lines with 6-7 layers of tags it becomes a mess just looking through it. Especially as many tags are not named the same as they are in the IDE.

What I hoped to have is that the conflict to be changed in such a way an xml-reading library can read it. - For example that the .r16 change is displayed into a comment (or subtag/attribute).

```<code><parentName>self
<!--.r16: objExplosion--></parentName>
</code>```

From that point on I can program a tool to help analyzing the conflict. - I can use one of the many xml libraries to write a simple application visualizing the tree.

Well I'm just surprised this hasn't been a problem to anyone else :/.

答:
It looks like you you saying that a file with unresolved conflicts breaks Gamemaker.

Well, I'd expect that regardless the file type or system. You need to resolve all the conflicts before building. There's no way that having a file marked with unresolved conflicts can keep the structure of that file valid.

If this was a C# or Java source file I'd expect to get compiler errors if I tried to build the project with the file in this state.


答:
Calling a getter should exhibit the same behavior as reading a field:

It should be cheap to retrieve the value

If you set a value with the setter and then read it with the getter, the value should be the same

Getting the value should have no side-effects

It should not throw an exception

Title: How Much Logic in Getters


答:
I don't think you find any VCS, which will work according to your needs currently (automagically).

Because all SCM (and diff-merge tools behind the scene) work with one string as minimal object of data, when you want to process *-entity (multi-sting) as integral object. You have to work with it by hand

EDIT for your EDIT2

I can't recall, how to resolve merge-conflicts easy in CLI SVN, but, if you can use any (good) GUI-capable differ-merger, which started on appearing of unclean merge, you'll have less troubles even with classic line-based merge: you see conflicts in context

Title: Version control programs for XML-files - merge/diff tool

Body:
My programming environment / language (gamemaker) gives the source files as "XML-files". Each resource has its own XML file. Where the properties (code is a property) are stored inside xml tags.

Is there a source control which can handle these? With subversion collisions don't seem to be handled correctly: when a collision happens, subversion breaks the XML structure. Which in turn breaks Gamemaker when updating.

EDIT (editing here as comments don't seem to handle newlines :P), an example of a source file that got "destroyed" by subversion:

```<code><object>
  <spriteName>sprBall</spriteName>
  <solid>0</solid>
  <visible>-1</visible>
  <depth>0</depth>
  <persistent>0</persistent>
<<<<<<< .mine
  <parentName>self</parentName>
=======
  <parentName>objExplosion</parentName>
>>>>>>> .r16
  <maskName><undefined></maskName>
  <events/>
</object>
</code>```

EDIT2: because of lack of experience with these tools, I asked the wrong question. So here a better wording:

In the example above an xml-file-reader will crash when trying to read the file. However manually resolving the conflict is "hard". (And in extreme cases impossible). "" doesn't say anything in itself. - As the first question becomes "parent name of what?"- An object? - which object? In this case one can see it quickly. However if the xml file reaches 100+ lines with 6-7 layers of tags it becomes a mess just looking through it. Especially as many tags are not named the same as they are in the IDE.

What I hoped to have is that the conflict to be changed in such a way an xml-reading library can read it. - For example that the .r16 change is displayed into a comment (or subtag/attribute).

```<code><parentName>self
<!--.r16: objExplosion--></parentName>
</code>```

From that point on I can program a tool to help analyzing the conflict. - I can use one of the many xml libraries to write a simple application visualizing the tree.

Well I'm just surprised this hasn't been a problem to anyone else :/.


问:
Right multi object dependance design
I need some help with a correct design.

I have a class called BufferManager. The push() method of this class reads data from a source and pushes it to a buffer repeatedly until there is no more data left in the source.

There are also consumer threads that read data from this buffer, as soon as new data arrives.

There is an option to sort the data before it comes to buffer. What I do right now is that BufferManager, instead of pushing data to the buffer, pushes it to another "sorting" buffer and starts a sorting thread. SorterManager class reads the data, sorts it in files and push()es the sorted data into the buffer.

There will be a bottleneck (I use merge sort with files) but this is something I can't avoid.

This is a bad design, because both BufferManager and SorterManager push data to a buffer (that consumers read from).  I think only BufferManager should do it.

How can I design it?

答:
Rambling answer follows :-)

I'm nit picking here, but your push() method should probably split out the reading of data from a source into another method, i.e. Follow the Single Responsibility Principle (SRP)

What sort of buffer do you have? I'm curious since you state that you have multiple consumers. I assume you're using a java.util.concurrent (j.u.c) data structure?

Depending on your buffer data structure, you might be able to push to the buffer in a sorted manner (whatever sorted means to you)

I think your design problem comes from higher up in the method call stack.  I think you're trying to model this:

```<code>BufferManager manager = new BufferManager();
manager.getDataFromSource();
if (sortData) {
    manager.sortData();
}

manager.push();
</code>```

Above is very much a strawman as the BufferManager methods could easily be static (depending on your mutability traits) and it depends on how you're reading in the data (bulk read or firehose style).

Hope that helps a little! And apologies for the non styling of the code block, not sure what's going on there, couldn't get the usual tool to work.

Title: Right multi object dependance design

Body:
Rambling answer follows :-)

I'm nit picking here, but your push() method should probably split out the reading of data from a source into another method, i.e. Follow the Single Responsibility Principle (SRP)

What sort of buffer do you have? I'm curious since you state that you have multiple consumers. I assume you're using a java.util.concurrent (j.u.c) data structure?

Depending on your buffer data structure, you might be able to push to the buffer in a sorted manner (whatever sorted means to you)

I think your design problem comes from higher up in the method call stack.  I think you're trying to model this:

BufferManager manager = new BufferManager();
manager.getDataFromSource();
if (sortData) {
    manager.sortData();
}

manager.push();

Above is very much a strawman as the BufferManager methods could easily be static (depending on your mutability traits) and it depends on how you're reading in the data (bulk read or firehose style).

Hope that helps a little! And apologies for the non styling of the code block, not sure what's going on there, couldn't get the usual tool to work.


答:
It's generally better for your site to be able to generate all content server-side. Bots might not implement Javascript and if there's content which can only be shown by using JS, you might end up with content not indexed by search engines.

If that's a concern for your site, I would implement all content rendering server-side and make sure all content has an URL which can be reached and rendered without Javascript.

Then, if you want to use Javascript, you can reuse the server-side programming; either use Javascript to fetch the HTML (either full or a fragment) which is generated server-side and plonk it down on the page. If you are using MVC or something similar, you might be able to obtain the Model easily in JSON format and do the View stuff in Javascript too.

If your site is not concerned with crawling, do not want your content to be accessible from URLs, etc. (i.e. your site is not really a web site), feel free to do everything in JS (i.e. GMail is not a "web site", it's an application- thus it's not strange that it's mostly JS).

Title: Generating presentation elements with Javascript vs PHP

Body:
What are the pros and cons of generating dynamic pages with javascript vs doing it in PHP?

As an example, I want to display certain records from some database in a table and I'm considering the following approaches:

Use Javascript to get some response in JSON from some PHP page, then dynamically build the table in Javascript.

Write some PHP in the page which will make the query and iterate through the result set echoing the table markup.

What are the pros and cons of each approach?


答:
It's difficult to say without more context - in your example, why is adding the if statement not the correct fix?  Is it because there's supposedly some other block of code in there somewhere that is supposed to be dealing with that input?

How often bandage fixes are used depends on a number of things such as how complex the code is, whether the person most familiar with the code is available (the person responsible for Craig's 20-year-old COBOL routine may have left the company years ago) and the timescales involved.

With a deadline staring you in the face, you will sometimes plump for the safer fix, even if it is just slapping a plaster on rather than fixing the root cause.  That's ok as long as you don't make things worse, but it's important to track the fact that it's still not correct and still needs to be fixed properly.

Title: How common are "bandage" fixes?

Body:
Imagine the following scenario:

You've detected that your (or someone else's) program has a bug - a function produces the wrong result when given a particular input. You examine the code and can't find anything wrong: it just seem to bog out when given this input.

You can now do one of two things: you either examine the code further until you've found the actual cause; or you slap on a bandage by adding an if statement checking if the input is this particular input - if it is, return the expected value.

To me, applying the bandage would be completely unacceptable. If the code is behaving unexpectingly on this input, what other input that you've missed will it react strangely to? It just doesn't seem like a fix at all - you're just shoveling the problem under the rug.

As I wouldn't even consider doing this, I'm surprised at how often the professors and books keep reminding us about how applying "bandage" fixes is not a good idea. So this makes me wonder: just how common are these kinds of "fixes"?


答:
SemanticDesign produce a line of language sensitive tools. Maybe you might be interested in checking those out.

Short of that, as 'Badger said, XML is a text file like any other, save of structure, and normal VCS's should work.


问:
Is it considered bad practice to have PHP in your JavaScript
So many times on this site I see people trying to do things like this :

```<code><script type="text/javascript">
  $(document).ready(function(){

     $('<?php echo $divID ?>').click(funtion(){
       alert('do something');
     });

  });
</script>
</code>```

I don't think that this is some sort of pattern that people naturally fall into. There must be some sort of tutorial or learning material out there that is showing this, otherwise we wouldn't see it so much. What I'm asking is, am I making too big a deal of this or is this a really bad practice?

EDIT :
Was speaking to a friend of mine about this who often puts ruby in his JavaScript and he brought up this point.

Is it ok to dynamically place application wide constants in your JavaScript so you don't have to edit two files. for example...

```<code>MYAPP.constants = <php echo json_encode($constants) ?>;
</code>```

also is it OK to directly encode data you plan to use in a library

```<code>ChartLibrary.datapoints = <php echo json_encode($chartData) ?>;
</code>```

or should we make an AJAX call every time?

答:
I would say that in general don't do it. However if you want to pass data from PHP -> Javascript it would not strike me as crazy to have an inline Javascript block where you have code of the form shown bellow. Here the code is just passing data from php to javascript, not creating logic on the fly or the like. The good part of doing this vs an ajax call is that the data is available as soon as the page loads and does not require an extra trip to the server. </p>

```<code><script>
window.config = <?php echo json_encode($config);?>;
</script>
</code>```

<p>Of course an other option is to build a javascript config file from PHP via some form of build script that will put that into a .js file. </p>

OwnerDisplayName: Greg Guida

Body:
I would say that in general don't do it. However if you want to pass data from PHP -> Javascript it would not strike me as crazy to have an inline Javascript block where you have code of the form shown bellow. Here the code is just passing data from php to javascript, not creating logic on the fly or the like. The good part of doing this vs an ajax call is that the data is available as soon as the page loads and does not require an extra trip to the server.

<script>
window.config = <?php echo json_encode($config);?>;
</script>

Of course an other option is to build a javascript config file from PHP via some form of build script that will put that into a .js file.


答: Generally speaking, you can write in whatever language you want, as long as you expose a C binding then virtually any language can bind to it.</p>

Title: Choosing language to write general library in

Body:
I'm about to start writing a library to support machine learning algorithms (decision trees, ANNs, Bayes nets, etc.), and I'm planning on making this a very general library. By this, I mean I want to be able to plug this module into as many languages as possible.

To clarify, here's why I've started writing it in C++ (Windows headers):

I know I can import C++ libraries into C#, and I've heard you can import C++ into Python. So, obviously, the library can be used in 3 languages, possibly 4 if I don't use system-specific headers.

Is there a language where I can cover a wider spread, weighted by popularity of languages? (For example, C# and C++ have pretty high weight to me because I use both frequently, Python less so.)


问:
Ways of marking changes being made to a file
I am looking for a lightweight way to notate changes made to a file. The obvious answer to this is a version control system. But this is more robust than necessary for what I would like to do. All I want is the functionality to compare an edited file to its original in a lightweight manner.</p>

答: diff is the answer to your explicit question.  But there's an implicit question as well.  You appear to think version control is heavyweight.  Some VCSes are indeed painful enough to get set up or deal with ongoing that there's a minimum threshold to get started with them.  Mercurial, however, works very easily and very nicely in a lightweight, no-server-needed, mode.


答:
You might want to try the Unreal Development Kit (Features). It might be a bit hard to learn about the interface. But the great thing about this is that it also has a visual scripting engine, so you don't need to be able to program to make something. He can then make something and program small parts of it himself. A downside might be that it uses its own scripting language.

Another engine I really like is Unity3D (Features). Unity doesn't have visual programming, but is does use two common languages: C# and JavaScript. It also supports a python dialect called Boo. These three can inter-operate. Unity also comes with a lot of finished scripts.

Title: A free game-development language?


答:
I know that you are looking for free languages and there are some good suggestions by other posters.  Since you are concerned about getting interesting results, fast and since Blitz seems like the kind of thing you'd like, except for the cost, I'd like to suggest Phrogram.  This used to be KPL (which was free).  It isn't free, but it's cheaper than Blitz and it has many of the same features that I think make it very suitable to use as a teaching language, especially for teenagers.

You can do some pretty sophisticated stuff with Phrogram and there is a pretty well established community of Phrogram and KPL users who have posted lots of code to learn from.

Title: A free game-development language?


答:
What are you trying to protect against? Is the concern that the bot will use excessive bandwidth or that they will get a copy of all your website content?

In either case an analysis of the log file after the fact will do nothing to prevent either. If you are concerned with someone stealing your content, what good does it do know that someone just did it last night? A little like locking the door after you have been robbed.

Much better to simply implement bandwidth throttling, simply limit the number of pages per unit time (minute/hour whatever) that you website will deliver to a specific IP address, or better still a block of IP addresses.

Remember that someone trying to steal your content may be very clever. The most likely will use multiple IP addresses.

Also be aware that there are hardware appliances that can be installed in a data center to do this in real-time.


答:
Time/deadline pressures are one reason.

If you are up against a tight deadline and you've got your boss breathing down your neck (possibly literally!) then doing this and thinking "I'll come back and fix this later" is very tempting and might be the only thing you can do.

Of course the number of times you actually go back and fix it properly are very few and far between because you have a new problem that needs fixing yesterday.

Title: How common are "bandage" fixes?


答:
I think that according to 'Clean Code' it should be split as much as possible, into something like:

```<code>public List<Stuff> getStuff() {
   if (hasStuff()) {
       return stuff;
   }
   loadStuff();
   return stuff;
}

private boolean hasStuff() {
    if (stuff == null) {
       return false;
    }
    if (cacheInvalid()) {
       return false;
    }
    return true;
}

private void loadStuff() {
    stuff = getStuffFromDatabase();
}
</code>```

Of course, this is complete nonsense, given that the beautiful form, which you wrote, does the right thing with a fraction of code that anyone understands at a glance:

```<code>public List<Stuff> getStuff() {
   if (stuff == null || cacheInvalid()) {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

It shouldn't be the caller's headache how the stuff is got under the hood, and particularly it shouldn't be the caller's headache to remember to call things in some arbitrary "right order".

Title: How Much Logic in Getters

Body:
I think that according to 'Clean Code' it should be split as much as possible, into something like:

public List<Stuff> getStuff() {
   if (hasStuff()) {
       return stuff;
   }
   loadStuff();
   return stuff;
}

private boolean hasStuff() {
    if (stuff == null) {
       return false;
    }
    if (cacheInvalid()) {
       return false;
    }
    return true;
}

private void loadStuff() {
    stuff = getStuffFromDatabase();
}

Of course, this is complete nonsense, given that the beautiful form, which you wrote, does the right thing with a fraction of code that anyone understands at a glance:

public List<Stuff> getStuff() {
   if (stuff == null || cacheInvalid()) {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}

It shouldn't be the caller's headache how the stuff is got under the hood, and particularly it shouldn't be the caller's headache to remember to call things in some arbitrary "right order".


答: Lots of good suggestions here, I'll just give a shout out to RoboCode.  There are lots of examples to tweak, and you can be up and running in just a few minutes.  It'll give him the flavor of programming, but he's not likely to learn the nuts and bolts of actually writing a program from scratch.  It's also Java based, for what that's worth.

Title: A free game-development language?


答: I think the modern-day equivalent of BASIC is Javascript.  Give him a simple HTML page that has an embedded script that creates a canvas and draws a shape on it, point him at some tutorials and see what happens.  Quick turnaround (save your changes and refresh the page) and decent debugging support.</p>

Title: A free game-development language?


答:
There are more important issues then just "appropriateness" here and you should base your decision on those. Mainly, the big decision here is wether you want to alow people to bypass the cache or not.

First, think about if there is a way to reorganize your code so all necessary load calls and cache management are done in the constructor/initializer. If this is possible you can create a class whose invariant allows you do to the simple getter from part 2 with the safety of the complex getter from part 1. (A win-win scenario)

If you cannot create such a class, decide if you have a tradeoff and need to decide wether you want to allow the consumer to skip the cache-checking code or not.

If it is important that the consumer never skip the cache check and you don't mind the performance penalties, then couple the check inside the getter and make it impossible for the consumer to do the wrong thing.

If it is OK to skip the cache check or it is very important that you are guaranteed O(1) performance in the getter then use separate calls.

As you might have already noted, I am not a big fan of the "clean-code", "split everything into tiny functions" philosophy. If you have a bunch of orthogonal functions that can be called in any order splitting them will give you more expressive power at little cost. However, if your functions have order dependencies (or are only really useful in a particular order) then splitting them only increases the number of ways you can do wrong things, while adding little benefit.

Title: How Much Logic in Getters


问:
My Asp.net MVC is running like a dodo ! Any recommendations
Following is the Url for my website, http://www.price-tag.org . If you visit any category link, you will see it performing very slow. For example, if you visit http://www.price-tag.org/Store/Section/Computers , you will see a lag before the sub categories are loaded.

This is just the very first phase and i have just added few categories to the database and nothing much. If it's working like this in the very beginning, what will happen when I start adding products.

I am using Entity Framework Code-first approach. Following is the code for one of the action that retrieves the list of categories.

```<code>PriceCompareEntity pe = new PriceCompareEntity();
    //
    // GET: /Store/
public ActionResult Section(string id)
{
    if (!string.IsNullOrEmpty(id))
    {
        var catsAndSub = pe.Categories.Where(cat => cat.Name == id).FirstOrDefault();
        if (catsAndSub == null || catsAndSub.ParentCategoryId != null)
        {
            return View("NoSuchRootCat");
        }
        else
        {
            ViewBag.Title = catsAndSub.MetaTitle;
            ViewBag.Description = catsAndSub.MetaDescription;
            ViewBag.Keywords = catsAndSub.MetaKeywords;
            return View(catsAndSub);
        }
    }
    else
    {
        return View("NoSuchRootCat");
    }
}
</code>```

I am really worried and bit disappointed. After so much of hard work for last month or two, the results aren't any good. If things are going to be this slow, my whole project will sink. Can't imagine how slow will it be if i add a few hundreds of products to the site. Nobody's gonna bother visiting a dodo website.

Have I done something wrong in the development ? And What can i do to get things right and straight. While surfing net, i came across web cache and other stuff, but they are very advanced and need quite bit learning. Besides, my website isn't any facebook or SO with millions of user so going that advanced into the subject seems a far cry and will take a lot of time to get things done.

Update

I have taken down the website, so links might not show the original content.

答:
In response to Matthieu's comment the problem likely isn't Linq though as the additional cost for using Linq queries is trivial.  The performance bottleneck has to be one of the few options:

The database query that is generated by EntityFramework is inefficient and causing a performance bottleneck.  Turn SQL logging on and view the Category queries being sent to the database.  If they appear to be okay then try running an Explain Plan on them for more detailed information on how the database engine is interpreting the query.  Perhaps your database needs updated statistics or more indexes?

It could be underpowered hardware.  Look closely at system resources and make sure they are sufficient.

Did you rule out the ASP.NET first-load wait time?  When ASP.NET pages are accessed for the first time after a deployment, IIS will compile them on request.  This page compilation can take awhile but it only happens after a deploy or change to pages.

EDIT: From Wikipedia on SQL Server CE - Microsoft SQL Server Compact (SQL CE) is a compact relational database produced by Microsoft for applications that run on mobile devices and desktops.  also SQL CE databases reside in a single .sdf file,[12] which can be up to 4 GB in size

So basically SDF files are intended to be used as relational datastores for stand-alone desktop applications and embedded devices.  The process that is using it shares the same memory pool, meaning that a process must lock the file to use it.  This means that only a single user could be using your website at the same time.

Based on all of this information, SDF files are clearly not intended for web applications.


答:
Are you talking about really large graphs -- 10+ GB?
Google uses it's own framework Pregel for that: http://googleresearch.blogspot.com/2009/06/large-scale-graph-computing-at-google.html

There now are quite a few open-source frameworks that copy that approach, some are discussed in http://blog.acaro.org/entry/google-pregel-the-rise-of-the-clones.

For smaller graphs that fit within the memory of a single computer there have been libraries for a long time, probably the most well known one is Boost Graph.

Title: Tool for large scale graph analysis

Body:
What are the best tools / frameworks / libraries available to implement and run algorithms on graphs?

In particular I need a tool that can load a set of nodes, edges and values assigned to these edges and then allows me to perform operations on them.

I already found R but I'm wondering if there is a more "programmer friendly" tool available?


问:
C# Design, many properties, complex constructor and equality
I'm still a relative novice with OOP, so I am still trying to understand some of the best practices for how to design "good" objects.  I know this question is probably a rather subjective, which is why I am here rather than on stackoverflow.

I am designing an object that will have 20 separate string properties, none of which are required.  These constraints are fixed and cannot be changed as it is an implementation of an outside data source that I have no control over.

The design problem I am running into is how to effectively construct an instance of the object and be able to compare equality by comparing each field without violating normal best practices.

A 20 argument constructor seems very wrong, especially since every field is a string, and there are cases where many of them will be null.  I could use the optional arguments in C#4 to reduce the number of arguments that are actually called, but since everything is a string, I would have to use named parameters when calling the constructor, and that seems that it would be even uglier.

I have thought about trying to group the properties into smaller classes, but the most logical grouping still has an object with 10 properties, and at least half of the remaining properties have no logical grouping.

I could give each property a public setter, but that would make the object mutable, and thus complicate matters for overriding GetHashCode().  And I really don't need the object to be mutable.  Once it is built, there should never be a reason to change it, but I don't want to rely on that because who knows what someone will try to do with it.

Implementing IEquatable<T> is a possibility for the equality test, but my understanding is it is recommended to also override Equals(object obj) and GetHashCode() when implementing IEquatable so all Equals methods have the same behavior.

Is this an edge case where overriding Equals without overriding GetHashCode should be done?  I don't intend on using this object as a key in a dictionary or as a member of a HashSet, but I can't predict what someone else would try to do in the future.

Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own Compare() method?

Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method?

EDIT:
In response to Sign's comment, the purpose of the object is ultimately to be able to compare the data from the outside data source to our internal data to ensure it is accurate.  Both data sets contain address information, but they are broken up differently.

The internal data, is generally stored as a typical address (Street, City, State, Postal Code, County, Country), but there are variations when you have a suite/apartment # or a floor in a building.

The external data is broken down even further into smaller pieces.

So this object is supposed to be a common link between the 2 data sources and allow the user to compare like fields for equality.

EDIT #2:
Ultimately, I chose Doc Brown's answer because a modified version of his dictionary idea (with Enums as Keys instead of strings) was the simplest way to go without having a messy constructor and still provide the immutability I was hoping to have.  In the long term, I am going to experiment with some of Oliver's suggestions as some of his edits did have a lot to offer.

答:
If you require your object to be immutable, there is obviously no other way than providing the 20 strings through the constructor. And if you want to be able to leave some of the strings out, you must say which arguments you are providing and which are not, which leads you to some form of named parameters. Of course, besides the possibilities you mentioned by yourself, you can also

provide the 20 arguments by a list of strings

provide them by a dictionary (key=>value, where "key" is the attribute name)

provide them by an object of a helper class, which has the same 20 properties with getters and setters, so this one won't be immutable

It may also be a good idea to implement Equals and GetHashCodeby utilizing reflection, looping over all public string properties of your class.

ContentLicense: CC BY-SA 4.0


问:
Web pages in UML sequence diagrams?
In my current project, we have an ongoing discussion about whether or not it's a good idea to include an artifact representing a web page in an UML sequence diagram for a web application, making explicit which page starts a business interaction.

I think it's a bad idea to include a web page, for me a sequence diagram should be about business logic and the interactions between business objects, and not include presentation concerns such as web pages. If I were to include a web page it'd be in a navigation diagram. Also, in my experience I had not seen web pages included in sequence diagrams, up until now.

What's the recommendation/best practice on this? Should we include an artifact representing a web page in each of our sequence diagrams, or not?

EDIT :

It'd be ideal if the answers quoted design/modeling guidelines, books on UML, etc. arguing in favor or in opposition to including presentation artifacts in UML design diagrams. So far I haven't found an authoritative source that I can quote on the subject, instead of personal opinions.

答: The page doesn't actually start the interaction, does it?  It's going to be an Ajax call or an HTTP GET or POST to a back-end component that does it.  In which case, I'd leave the page out of it and start with the back-end component, since (theoretically) the triggering event could come from any page.

Title: Web pages in UML sequence diagrams?


答:
It is the abstraction that you form for the web page that matters -

For example, when users fill up a form and send a requests - the web page is essentially a source of initiation or response to user for a sequence of dialog (with say a back-end). In that case, the role of web page is no different from the client application in similar scenarios.

Sometimes, a key request may go to end server/service after several iteration with users - for example user may enter wrong password or user is not logged in which is redirected - such things can be omitted from the regular work flow assuming that user is authenticated.

If there are intermediate actions you want to define between how user interacts with buttons or other elements inside the page and how the page needs to react to it - in such cases UML could be a bad idea;

You need to define the exact purpose and scope of interaction to be plotted in appropriate sequence diagram.

Title: Web pages in UML sequence diagrams?

Body:
In my current project, we have an ongoing discussion about whether or not it's a good idea to include an artifact representing a web page in an UML sequence diagram for a web application, making explicit which page starts a business interaction.

I think it's a bad idea to include a web page, for me a sequence diagram should be about business logic and the interactions between business objects, and not include presentation concerns such as web pages. If I were to include a web page it'd be in a navigation diagram. Also, in my experience I had not seen web pages included in sequence diagrams, up until now.

What's the recommendation/best practice on this? Should we include an artifact representing a web page in each of our sequence diagrams, or not?

EDIT :

It'd be ideal if the answers quoted design/modeling guidelines, books on UML, etc. arguing in favor or in opposition to including presentation artifacts in UML design diagrams. So far I haven't found an authoritative source that I can quote on the subject, instead of personal opinions.


答: It seems like you want two constructors one for each type of input data.  If that data is already contained in an object you could take that in.  The Dictionary constructor doesn't seem like a good idea since an arbitrary set of data is not going to be sufficient to do anything with(an object with just a country and a street name would do no good). </p>

Title: C# Design, many properties, complex constructor and equality

Body:
I'm still a relative novice with OOP, so I am still trying to understand some of the best practices for how to design "good" objects.  I know this question is probably a rather subjective, which is why I am here rather than on stackoverflow.

I am designing an object that will have 20 separate string properties, none of which are required.  These constraints are fixed and cannot be changed as it is an implementation of an outside data source that I have no control over.

The design problem I am running into is how to effectively construct an instance of the object and be able to compare equality by comparing each field without violating normal best practices.

A 20 argument constructor seems very wrong, especially since every field is a string, and there are cases where many of them will be null.  I could use the optional arguments in C#4 to reduce the number of arguments that are actually called, but since everything is a string, I would have to use named parameters when calling the constructor, and that seems that it would be even uglier.

I have thought about trying to group the properties into smaller classes, but the most logical grouping still has an object with 10 properties, and at least half of the remaining properties have no logical grouping.

I could give each property a public setter, but that would make the object mutable, and thus complicate matters for overriding GetHashCode().  And I really don't need the object to be mutable.  Once it is built, there should never be a reason to change it, but I don't want to rely on that because who knows what someone will try to do with it.

Implementing IEquatable<T> is a possibility for the equality test, but my understanding is it is recommended to also override Equals(object obj) and GetHashCode() when implementing IEquatable so all Equals methods have the same behavior.

Is this an edge case where overriding Equals without overriding GetHashCode should be done?  I don't intend on using this object as a key in a dictionary or as a member of a HashSet, but I can't predict what someone else would try to do in the future.

Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own Compare() method?

Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method?

EDIT:
In response to Sign's comment, the purpose of the object is ultimately to be able to compare the data from the outside data source to our internal data to ensure it is accurate.  Both data sets contain address information, but they are broken up differently.

The internal data, is generally stored as a typical address (Street, City, State, Postal Code, County, Country), but there are variations when you have a suite/apartment # or a floor in a building.

The external data is broken down even further into smaller pieces.

So this object is supposed to be a common link between the 2 data sources and allow the user to compare like fields for equality.

EDIT #2:
Ultimately, I chose Doc Brown's answer because a modified version of his dictionary idea (with Enums as Keys instead of strings) was the simplest way to go without having a messy constructor and still provide the immutability I was hoping to have.  In the long term, I am going to experiment with some of Oliver's suggestions as some of his edits did have a lot to offer.


答:
There is absolutely no problem with implementing GetHashCode() whether your object is immutable or not. If it is immutable, the hashcode can be precomputed; if it is mutable, the hashcode needs to be recalculated each time the GetHashCode() method is invoked. And since your object consists of nothing but 20 strings, which are immutable, and therefore their hashcodes are already computed, computing your hashcode is close to trivial. Just multiply the hashcodes of your non-null string members together, or search stackoverflow for some slightly better hashcode algorithm.

Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method?

I am a fanatic proponent of immutable objects, so I would advice you to make yours immutable. And I would not pass a dictionary or a list to the constructor; I would pass 20 separate arguments, there is nothing wrong with that, and there is nothing gained doing it any other way. Any other way is bound to move some of the checking that the compiler will do for you at compile time, to checking that you will have to do yourself at runtime: always a bad idea.

Is this an edge case where overriding Equals without overriding GetHashCode should be done? I don't intend on using this object as a key in a dictionary or as a member of a HashSet, but I can't predict what someone else would try to do in the future.

For IEquatable<T> it is true that you do not, strictly speaking, need to implement GetHashCode(), except to avoid the warning that you will receive if you don't, but good practice is to always implement GetHashCode(), precisely because someone might try to use it in the future.

Note: Since you will be making your object immutable, (won't you?) you can precompute your hashcode, and store it with the object, so that the Equals() method can first compare hashcodes and return immediately if they do not match, rather than always doing a full comparison. In practice you do not need to do tricks like that unless you have already established that you have a performance issue, but it is a trick worth keeping in mind.

Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own Compare() method?

I do not know what you mean by this question. You will be implementing your own Equals() method, and it will be a series of if( !Object.Equals( MyField1, other.MyField1 ) ) return false;


答: Personally, I would expose the requirement of Stuff via a parameter in the constructor, and allow whichever class is instantiating stuff to do the work of figuring out where it should come from. If stuff is null, it should return null. I prefer not to attempt clever solutions like the OP's original because it's an easy way to hide bugs deep inside your implementation where it's not at all obvious what might be going wrong when something breaks.</p>

Title: How Much Logic in Getters


答: Are the table fields in your where clause indexed? You don't want to be searching the tables for text(varchar) fields when you can be using indexes. Primary keys are probably taken care of by the framework.</p>

Title: My Asp.net MVC is running like a dodo ! Any recommendations

Body:
Following is the Url for my website, http://www.price-tag.org . If you visit any category link, you will see it performing very slow. For example, if you visit http://www.price-tag.org/Store/Section/Computers , you will see a lag before the sub categories are loaded.

This is just the very first phase and i have just added few categories to the database and nothing much. If it's working like this in the very beginning, what will happen when I start adding products.

I am using Entity Framework Code-first approach. Following is the code for one of the action that retrieves the list of categories.

```<code>PriceCompareEntity pe = new PriceCompareEntity();
    //
    // GET: /Store/
public ActionResult Section(string id)
{
    if (!string.IsNullOrEmpty(id))
    {
        var catsAndSub = pe.Categories.Where(cat => cat.Name == id).FirstOrDefault();
        if (catsAndSub == null || catsAndSub.ParentCategoryId != null)
        {
            return View("NoSuchRootCat");
        }
        else
        {
            ViewBag.Title = catsAndSub.MetaTitle;
            ViewBag.Description = catsAndSub.MetaDescription;
            ViewBag.Keywords = catsAndSub.MetaKeywords;
            return View(catsAndSub);
        }
    }
    else
    {
        return View("NoSuchRootCat");
    }
}
</code>```

I am really worried and bit disappointed. After so much of hard work for last month or two, the results aren't any good. If things are going to be this slow, my whole project will sink. Can't imagine how slow will it be if i add a few hundreds of products to the site. Nobody's gonna bother visiting a dodo website.

Have I done something wrong in the development ? And What can i do to get things right and straight. While surfing net, i came across web cache and other stuff, but they are very advanced and need quite bit learning. Besides, my website isn't any facebook or SO with millions of user so going that advanced into the subject seems a far cry and will take a lot of time to get things done.

Update

I have taken down the website, so links might not show the original content.


答:
It's very difficult to tell. Have you tried using some Profiler to see what's the bottleneck?

EQATEC (free): http://eqatec.com/Profiler/Home.aspx

ANTS (commercial): http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/


答:
There is a Haskell library called Gloss, which has a really simple interface and has been used to teach children:

http://cdsmith.wordpress.com/2011/09/28/haskell-for-kids-week-7/

It can be tried online too:

http://dac4.designacourse.com:8000/anim

Title: A free game-development language?


答:
I can't understand how no one talks about Games Factory!
This is one of the best resources to build quickly a computer game, without a knowledge of programming.

http://www.clickteam.com/website/usa/downloads/index/7

It consists of the story board editor - with frames.
You put different objects which can be controleed by various ways by the player
(Platform movement, 8 direction, etc..)

The most important aspect is the event editor - it is a huge matrix, which you use to define what happens from pre-defined rules(Like - object(1) moved to end of screen, location of object is > 100, etc...).

Title: A free game-development language?


问:
Who usually does the use case analysis in the team?
I've just started my first IT job in a team with two developers (junior and senior), a project leader and an architect. My role is not yet completely defined and I said I'd be ok with both programming or testing. For now they put me on use case analysis since the PL says that it would leverage my analytical skills (I'm a science phd).

Now the question is who's usually responsible for use case analysis? How usual is it to put a newbie on it?

The hidden fear I have is: are they trying to keep me away from programming (after two weeks I still haven't SEEN a line of code...)?

答:
Were you hired as a software developer? It doesn't sound like it to me.

You said your role is not completely defined. This means they can ask you to do almost anything that is realistically related to IT. This includes analysis work. And, if they want to leverage your analytical skills, it sounds like you might be doing more analysis work than actually writing code.

I don't think it's unusual at all to put a development newbie on analysis work, since you are clearly not a newbie at that, given your Phd in the sciences.

I've been writing software for 20+ years. I've done my share of analysis work, and I've worked for companies where the 'Analysts' do this sort of thing.