答:
Ideally it would be best to query the database and store the data returned for future use. Creating enums for specific tables where you need the IDs duplicates data that you can get another way which should be avoided. That being said however, in many cases it makes more sense in practice to create enums with this data and update them as you update the information in those tables, because the effort involved in doing it the "correct" way only pays off if the tables change somewhat frequently. The effort involved to update an enum once a year or so by addiing an entry or two isn't significant.

Don't create anything as global though, create a constants class and expose it only where you need it. Also it would be best to go ahead and create the entire table as an enum now, this method can get really ugly if the enum gets out of sync with the database.

Title: Should I create an Enum mapping to my database table

Body:
I have a database table containing a list of systems relevant to the tool I am building, mostly in-house applications, or third-party systems we receive data from. This table is added to infrequently, approx every 2 months.

One of these systems is Windows itself, which is where we store our users' LANs, and I now need to explicitly reference the ID relating to Windows to query for user name, team etc. I know it would be bad practice to embed the ID itself into the code, so my question is what would be the best way to avoid this? I'm assuming my options are:

create a global constant representing this ID

create a global enum containing all systems now

create a global enum and add systems to it as & when they are required in the code

retrieve the ID from the database based on system name

I appreciate this may seem a trivial question, but I am going to have many situations like this during the course of this build, and although we are in complete control of the database I would like to conform to best practice as far as possible.

Many thanks!


问:
Should I create an Enum mapping to my database table
I have a database table containing a list of systems relevant to the tool I am building, mostly in-house applications, or third-party systems we receive data from. This table is added to infrequently, approx every 2 months.

One of these systems is Windows itself, which is where we store our users' LANs, and I now need to explicitly reference the ID relating to Windows to query for user name, team etc. I know it would be bad practice to embed the ID itself into the code, so my question is what would be the best way to avoid this? I'm assuming my options are:

create a global constant representing this ID

create a global enum containing all systems now

create a global enum and add systems to it as & when they are required in the code

retrieve the ID from the database based on system name

I appreciate this may seem a trivial question, but I am going to have many situations like this during the course of this build, and although we are in complete control of the database I would like to conform to best practice as far as possible.

Many thanks!

答:
Short Answer: i would keep my data in the database. The last option is good one.

retrieve the ID from the database based on system name

In order to deal gracefully with IDs that you are referring, you may use Dictionaries to load all reference Id's from database table(s) within your application. Depending on how frequently this Id's may change, you may also cach this dictionary for a much better performance.

ContentLicense: CC BY-SA 3.0


问:
Is it bad practice to pass instances through several layers?
In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I don´t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.

答:
Quick Answer: There is nothing wrong in passing instances of objects. As also mentioned, point is to skip assigning this reference in all the layers potentially causing a dangling reference or memory leaks.

In our projects, we do use this practice to pass DTOs (Data transfer object) between  layers and it is very helpful practice. We also do reuse our dto objects to construct more complex once, like for summary information.


问:
What is occurring in the world of server-side technologies in regards to the mobile app boom?
With mobile technologies becoming increasingly popular what is happening on the server-side with most of these apps when they need to communicate with a back end?

I'm used to the world of technology from 10 years ago when most resources were accessed by requesting a dynamic web page that behind the seen used a server-side language to get the information it needed from a relational database.

Is this still the case, and if not, what are the big changes?

答:
REST is half the story. The more interesting thing than lighter-weight protocols on the wire is lighter-weight web app servers and stacks -- the mass scale requests for small datagrams versus comparatively thick rendered HTML means you have different requirements. Some examples:

node.js is probably the cannonical example of this. Most folks get hung up on the javascript-on-the-server feature, but that is a red herring -- cool for the kids who can't progress beyond js but it don't matter. The really nifty part is the asynchronous nature making it scale insanely, especially while serving small, sharp RESTful services. Some other stacks with similarities would be twisted for python or manos de mono for .NET.

nginx uses alot of the same evented IO (libuv) that node.js does, and it is cleaning up the server market in some circles. Much more focused than apache and insanely fast.

Thin server stacks are popping up in environments which traditionally had thick frameworks that made lots of presumptions. IE, in ruby you've got sinatra to counterbalance rails. In python you've got flask [and others] to counterbalance django. In .NET you've got the WebAPI to counterbalance MVC and WebForms. All of the stacks I mentioned are very, very thin and are more (or totally) focused on serving datagrams and not web pages. None of the ones I mention feature the sorts of templating and ORMs one expects out of a typical web stack these days.

All that said, more often than not someone is serving their mobile app by hacking the existing 10 year old server-side web app to serve json on a different HTTP endpoint. World ain't changed that much -- management will still limp along on 2 wheels and a doughnut if they think they can get away with it.


答:
Technologies

RESTful API using JSON as serialization
— Same API is used by native apps, hybrid apps and mobile web apps. Even in the former case client side templates are often used (see excellent example in "Leaving JSPs in the dust: moving LinkedIn to dust.js client-side templates")

Lightweight, asynchronous (event driven) servers — no more pre-fork Apache. Nginx, node.js, Twisted, Tornado etc. are used now.

OAuth / social login — Users expect not to have to register an account for each individual app. Thus most apps allow login with FB, TW and other providers. For FB both Android and iOS provide Single-Sign-On option.

Things to consider

Mobile networks have very high latencies;

It's normal for clients to loose connections;

It's normal for a client to change IP during session;

Mobiles are nowhere near as powerful as desktops/laptops;

Title: What is occurring in the world of server-side technologies in regards to the mobile app boom?

Body:
With mobile technologies becoming increasingly popular what is happening on the server-side with most of these apps when they need to communicate with a back end?

I'm used to the world of technology from 10 years ago when most resources were accessed by requesting a dynamic web page that behind the seen used a server-side language to get the information it needed from a relational database.

Is this still the case, and if not, what are the big changes?


问:
TDD - Outside In vs Inside Out
What is the difference between building an application Outside In vs building it Inside Out using TDD?

These are the books I read about TDD and unit testing:

Test Driven Development: By Example

Test-Driven Development: A Practical Guide: A Practical Guide

Real-World Solutions for Developing High-Quality PHP Frameworks and Applications

Test-Driven Development in Microsoft .NET

xUnit Test Patterns: Refactoring Test Code

The Art of Unit Testing: With Examples in .Net

Growing Object-Oriented Software, Guided by Tests--->This one was really hard to understand since JAVA isn't my primary language :)

Almost all of them explained TDD basics and unit testing in general, but with little mention of the different ways the application can be constructed.

Another thing I noticed is that most of these books (if not all) ignore the design phase when writing the application. They focus more on writing the test cases quickly and letting the design emerge by itself.

However, I came across a paragraph in xUnit Test Patterns that discussed the ways people approach TDD. There are 2 schools out there Outside In vs Inside Out.

Sadly the book doesn't elaborate more on this point. I wish to know what is the main difference between these 2 cases.

When should I use each one of them?

To a TDD beginner which one is easier to grasp?

What is the drawbacks of each method?

Is there any materials out there that discuss this topic specifically?

答:
You should add Agile Prinicples, Patterns and Practices in C# to that list. I don't know why he tacked on "in C#" on the end. The books is not the language at all and the only reason it didn't get 5 stars on amazon is from people who were disappointed in C#-ness of his examples.

The author, advocates that whenever possible you should try to write code outside-in and rely heavily on evolutionary design, and I agree with his statement. His reasoning is that as we add functionality, our design will always evolve. If we start with low-level components as features are added, we'll realize those components are not doing what we'd like them to do, or that things need to be moved around. This could get rather expensive especially if every time you move functionality from one class into another, you need to do the same move in all the unit test projects.

On the other hand, if you determine what your application is supposed to do in the first place, you code for external interface.  As features get added and code under test grows in size, you refactor your application into more classes, but while this refactoring effort is going on, the original unit tests you've written remain valid.  So you start completely on the outside and continue refactoring into more and more low-level classes, while adding additional unit tests to those inner classes, but you would rarely have to move around and rewrite your unit tests.

However, if you identify a specific low-level subsystem that your application will need (and maybe your company already has a need for such subsystem in other applications), this would be the time to start with a low-level building block first and then build the app on top of that.

Title: TDD - Outside In vs Inside Out


问:
Visual C++, CMap object save to blob column
I have a MFC CMap object, each object stores 160K~ entries of long data. I need to store it on Oracle SQL. We decided to save it as a blob. Since we do not want to make additional table, we also thought about saving it as local file, with the SQL column pointing to that file.  We would prefer to just keep it as blob on the server and clear the table every couple of weeks.

The table has a sequential key as ID, and 2 column of time. I need to add the blob column in order to store on every row that CMap.

Can you recommend a guide to do this approach (read/write Map to blob or maybe a clob)? Thanks.

答: You're looking for serialization, which turns a structured object into a blob. MFC has explicit support for it.


问:
How to prevent duplicate data access methods that retrieve similar data?
In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method:

```<code>AssetDto GetAssetById(int assetId)
</code>```

A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following:

```<code>AssetDto GetAssetWithApproversById(int assetId)
</code>```

A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc):

```<code>AssetDto GetAssetWithQuestionsById(int assetId)
AssetDto GetAssetWithOwnersById(int assetId)
AssetDto GetAssetWithRunningRequestsById(int assetId)
</code>```

And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear.

You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations.

Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?

答:
When dealing with large object, this is really common. While adding new methods increases performance, it significantly decreases the maintainability. And again you need to choose between those two.

I suggest you have a method that returns (not necessarily the smallest) commonly used data, another that returns the whole object, and probably a few more for the most expensive resources.

Another approach is to have methods that return only the necessary fields of the object, like
AssetQuestions GetAssetQuestionsById(int assetId) or Owners GetAssetOwnersById(int assetId).

Along with this you need to establish some rules regarding retrieving data. For example, if someone needs 5 fields of the object, and there is an existing method returning 8, the existing method should be used.


答:
Syntax-wise, I'd create an intermediate query-building object with a fluid interface:

```<code>// all the basic, cheap to query fields
AssetDto a = AssetRetriever(asset_id).fetch()

// some common expensive fields
AssetDto a = AssetRetriever(asset_id).withOwner().withQuestion().fetch()

// numerous less common fields may not command dedicated methods
AssetDto a = AssetRetriever(asset_id).withFields("foo", "bar").fetch()

// Better yet, use an enum and enjoy static checking
AssetDto a = AssetRetriever(asset_id).withFields(F_OWNER, F_QUESTION).fetch()
</code>```

I hope it's obvious enough to implement. The only method that will actually touch the database is fetch().

Title: How to prevent duplicate data access methods that retrieve similar data?

Body:
In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method:

```<code>AssetDto GetAssetById(int assetId)
</code>```

A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following:

```<code>AssetDto GetAssetWithApproversById(int assetId)
</code>```

A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc):

```<code>AssetDto GetAssetWithQuestionsById(int assetId)
AssetDto GetAssetWithOwnersById(int assetId)
AssetDto GetAssetWithRunningRequestsById(int assetId)
</code>```

And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear.

You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations.

Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?

Body:
Syntax-wise, I'd create an intermediate query-building object with a fluid interface:

// all the basic, cheap to query fields
AssetDto a = AssetRetriever(asset_id).fetch()

// some common expensive fields
AssetDto a = AssetRetriever(asset_id).withOwner().withQuestion().fetch()

// numerous less common fields may not command dedicated methods
AssetDto a = AssetRetriever(asset_id).withFields("foo", "bar").fetch()

// Better yet, use an enum and enjoy static checking
AssetDto a = AssetRetriever(asset_id).withFields(F_OWNER, F_QUESTION).fetch()

I hope it's obvious enough to implement. The only method that will actually touch the database is fetch().


问:
In PHP, what are the different design patterns to implement OO controllers as opposed to procedural controllers?
For example, it's very straightforward to have an index.php controller be a procedural script like so:

```<?php

//include classes and functions

//get some data from the database
//and/or process a form submission

//render HTML using your template system

?>
```

Then I can just navigate to http://example.com/index.php and the above procedural script is essentially acting as a simple controller. Here the controller mechanism is a basic procedural script.

How then do you make controllers classes instead of procedural scripts? Must the controller class always be tied to the routing mechanism?

答:
No, I don't think an Object Oriented controller in such as scenario necessarily needs to be tied to the routing mechanism. You could use Facade or Command patterns to call a controller without it (the controller) ever knowing the details of that call (or, more precisely, without having the controller object know more than it needs to about the call).

IMHO the advantage of passing for procedural controllers to Object Oriented ones doesn't necessarily lie just in how well it can be isolated from the rooting part, but more in how you can more easily reuse and organize those OO controllers as opposed to procedural ones. What's the rough estimate of the percentage of similar behavior that all your procedural controllers have between them? You could put all that into one "base" OO controller, and then re-use it via inheritance or composition (preferably, the latter) to pass that common behavior to all your other controllers, without having to duplicate it each time in the code (or cross-importing the procedural scripts one in-to the other).

==== update

As per the comment below, here's an example inspired from Spring Framework's old (v2) MVC module:

one or more router objects. The router object(s) are configured with URL patterns and the corresponding controller objects for each pattern. This way, when the router is hit by a  request (which matches a certain URL pattern), it will create an object with that request's parameters (here you can but as many or as few details on the actual request as you like) and call the corresponding controller object passing him the request object

This way you have your controller not only isolated from the low level details of the request, but from the rooter as well (they communicate via an intermediate requet object, neither cares how it was produced or consumed, respectively)

multiple controller objects which map to one or more URL patterns each. Usually you'll create an interface for the controller and that's the only thing the router will know about each controller. Then you implement that interface into actual controllers according to each business need. Here you'll take the most advantage of OO, as you can encapsulate common behavior into an Abstract controller class which you can then extend for certain controllers, etc

finally you'll have one or more view resolver objects. These will be used by the controllers to know what view to show once they do their processing and create a model object. The view resolvers simply associate either URL pattern(s) or controller(s) to views.

as said earlier the controller will produce a model object. This guy will contain all the necessary data so that the view can update itself for the given action/workflow

Final considerations

according to what definition of MVC you embrace, this may or may not be a kosher implementation of the paradigm. In some MVC definitions it is said that the view has some kind of hooks or callbacks in the model such that when the model changes the view updates itself automatically, in other words, all the controller has to do is change the model and not worry about the view. In other definitions the view needs to be notified by the controller that the model has changed in order to update itself. You can go either way, usually to implement the first version, you'll need some JavaScript library to help you with that. If you wanna steer clear clear of JS you can just implement the second version, and just refresh the view (via controller) when the model changes.

make sure to keep your model, view and controller objects cleanly separated (as much as possible). The controller should only get the necessary request data, and construct the model accordingly. If going from request data to model is complicated, make separate service objects that deal with it and just have them return th model to the controller so that it can pass it to the view (and notify it if necessary). The controller only deals with getting input data and passing the model to the view. The model should be super dumb, no business logic or anything like that in it. It should just hold the data for the view. The view itself should only be concerned with presentation, i.e. with formatting the data for the user, not with business logic or other heavy treatment of the model data (the model should contain the final data to display).


问:
Figuring out the Call chain
Let's say I have an assemblyA that has a method which creates an instance of assemblyB and calls its MethodFoo().

Now assemblyB also creates an instance of assemblyC and calls MethodFoo().

So no matter if I start with assemblyB in the code flow or with assemlyA, at the end we are calling that MethodFoo of AssemblyC(). My question is when I am in the MethodFoo() how can I know who has called me? Has it been a call originally from assemblyA or was it from assemlyB?

Is there any design pattern or a good OO way of solving this?

答:
I am not aware of any generic or common patterns across programming languages. Most handle it by dedicated reflection APIs.

In .Net use the System.Diagnostics.StackFrame and System.Diagnostics.StackTrace classes. See https://stackoverflow.com/questions/12556767/how-to-get-current-line-number-for-example-use-at-messagebox-show/12556789#12556789 for an example. Other languages and environments may have equivalents.

Title: Figuring out the Call chain


问:
What is the precise definition of programming paradigm?
Wikipedia defines programming paradigm thus:

a fundamental style of computer programming

which is echoed in the descriptive text of the paradigms tag on this site.

I find this a disappointing definition. Anyone who knows the words programming and paradigm could do about that well without knowing anything else about it. There are many styles of computer programming at many level of abstraction; within any given programming paradigm, multiple styles are possible. For example, Bob Martin says in Clean Code (13),

Consider this book a description of the Object Mentor School of Clean Code. The techniques and teachings within are the way that we practice our art. We are willing to claim that if you follow these teachings, you will enjoy the benefits that we have enjoyed, and you will learn to write code that is clean and professional. But don't make the mistake of thinking that we are somehow "right" in any absolute sense.

Thus Bob Martin is not claiming to have the correct style of Object-Oriented programming, even though he, if anyone, might have some claim to doing so. But even within his school of programming, we might have different styles of formatting the code (K&R, etc). There are many styles of programming at many levels.

So how can we define programming paradigm rigorously, to distinguish it from other categories of programming styles? Fundamental is somewhat helpful, but not specific. How can we define the phrase in a way that will communicate more than the separate meanings of each of the two words—in other words, how can we define it in a way that will provide additional meaning for someone who speaks English but isn't familiar with a variety of paradigms?

答:
Thomas Kuhn defines paradigm in The Structure of Scientific Revolutions as:

Attempting to discover the source of that difference led me to recognize the role in scientific research of what I have since called “paradigms.” These I take to be universally recognized scientific achievements that for a  time provide model problems and solutions to a community of practitioners.

Merriam-Webster offers three definitions1, the third one being the most relevant:

example, pattern; especially: an outstandingly clear or typical example or archetype

an example of a conjugation or declension showing a word in all its inflectional forms

a philosophical and theoretical framework of a scientific school or discipline within which theories, laws, and generalizations and the experiments performed in support of them are formulated; broadly: a philosophical or theoretical framework of any kind

The term is quite commonly used and well understood in scientific environments, we don't need to further define it. A programming paradigm is simply a paradigm of the programming discipline, and that's about it.

The Wikipedia article you link to offers more of an explanation, perhaps targetted to people without a programming or other scientific background, than a definition. It's an encyclopaedia after all, not an authoritative software development reference.

1 Example is used prominently in the first two definitions, because paradigm (παράδειγμα) is the Greek word for it.


答:
I'm going out on a limb here and guessing you're looking for object oriented techniques for implementing instrumentation.

There are two immediate ways that come to mind, most commonly used would be the first I'm guessing:

Have a global (singleton or what have you) stack somewhere with which every method that executes immediately adds itself to. effectively maintaining a global call chain. You could but don't have to pop at the end of each method you're trying to instrument, common other instrumentation practices are to start a stopwatch at the beginning of your method and stop at the end to record the length etc.

Have a DI type framework that is a router for all method calls, which might behave more akin to message passing, and inside of this framework you would jot down in a stack every method call that occurs similar to above except it would be centralized to this one place.

I can't say I suggest #2 without maybe using some AOP framework or something but in all, maintaining your own stack trace on 100% of method calls is a bit of an extreme instrumentation in my eyes. Great for debugging type stuff and perhaps necessary if you aren't working in a reflexive language, but I would be sure I could turn anything like that off easily for production and do my best to keep it out of the way, which is why I don't really like #2 above.

Neither of these is necessary inside a reflexive language and should therefore not be implemented in C# except to illustrate crossing process boundaries. (caveat: they might be faster than reflection if done right, but the maintenance cost still makes them not worth it)

Title: Figuring out the Call chain

Body:
Let's say I have an assemblyA that has a method which creates an instance of assemblyB and calls its MethodFoo().

Now assemblyB also creates an instance of assemblyC and calls MethodFoo().

So no matter if I start with assemblyB in the code flow or with assemlyA, at the end we are calling that MethodFoo of AssemblyC(). My question is when I am in the MethodFoo() how can I know who has called me? Has it been a call originally from assemblyA or was it from assemlyB?

Is there any design pattern or a good OO way of solving this?


问:
Ideal programming language learning sequence?
What do you think? What is the ideal programming language learning sequence which will cover most of the heavily used languages and paradigms today as well as help to grasp common programming basics, ideas and practices?
You can even suggest learning sequence for paradigms rather than languages.

N.B. : This is port of the question I asked in stackoverflow and was closed for being subjective and argumentative.

答:
Scheme, C, C++

I will be biased and use the model my university currently uses for its core Computer Science curriculum. I was against it during my first year but in my later years I am grateful for it. The model is based on not requiring any programming experience but requiring the ability to learn.

Scheme

We are you are first learning programming, the less magic, the better. The teaching language of Scheme presents a clear and reasonable definition of a language, a really small set of axioms (the "magic") that you can build and expand on. Anyone who can understand functions in math can trace and reason Scheme programs. Starting with Scheme provides a clean yet powerful way to think about computation without worrying about the language specific details.

C

Moving from Scheme to C is a drastic one but allows you learn about the very important mapping of high level languages to low level languages. Learning the memory model (pointers, heap, stack etc.) and how programs are compiled and run, how pointers, stack and the heap work are essential skills. Through this low level understanding you can begin to analyze programs on a higher level (Big O). You can begin rolling your own abstract data types, playing with different implementations (say a simple hash table vs. a binary tree for a set).

C++

Through learning C and Scheme we begin to see different paradigms of programming languages and how they can apply to different problems. Now you can approach the scariest aspects of programming: choice and trade offs. Programming language choice can affect performance, readability, maintainability, robustness etc. For solving problems bigger than things you can hold in your head, this choice is great but also dangerous. C++ tries to make as few choices for the programmer as possible. Through learning C++ you will learn how to make these trade offs and choices yourself to solve your problems.

You might not use any of these languages in industry or ever touch them again, but the process of learning them helps you understand other languages you will use. Another aspect is you learn the tools around a specific language. Running gcc through the command line, learning Vim, stepping through a program using GDB, creating Make files, checking in code using SVN, writing shell scripts to automate testing etc.

Mind you the core curriculum also has other courses (computer architecture, data structures and algorithms, compilers,  operating systems etc.). So just merely learning these languages isn't enough to be proficient at programming.

ContentLicense: CC BY-SA 2.5


答:
IMHO you should ask yourself seriously why you think you need this.

If MethodFoo() behaves differently if called from assembly A or B, then the calling assembly is something like a hidden input parameter to MethodFoo() and may probably become the cause for unexpected or erroneous behaviour. So as an alternative, make that input parameter explicit: add an additional parameter to MethodFoo() which indicates the context or caller. This could be an enum, a string parameter or a reference to the calling assembly itself, depending on the intended behaviour change of MethodFoo().

Title: Figuring out the Call chain


答:
Interesting that no one has talked about Immutable objects yet.
I would argue that passing an immutable object around through all the various layers is actually a good thing rather than creating lots of short lived objects for each layer.

There are some great discussions of immutability by Eric Lippert on his blog

On the other hand I'd argue that passing mutable objects between layers is bad design.  You're essentially building a layer with the promise that surrounding layers won't alter it in a way to break your code.

Title: Is it bad practice to pass instances through several layers?

Body:
In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I don´t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.

ContentLicense: CC BY-SA 4.0


答:
Retrieve the ID from the database based on system name

All your other options involve duplicating the database data in your code.  Database and program design is usually a process of reducing data duplication, not increasing it.

If you were starting from scratch, and you didn't expect a new system very often and there were only a few systems, maybe you would start out with an enum.  When you got sick of recompiling and re-releasing the code every time you supported a new system, then you'd make a database table.  But since you already have a database table, I can't think of a reason not to use it.

I now need to explicitly reference the ID relating to Windows to query
  for user name, team etc.

Simple:

```<code>select u.user_name, u.team, u.other_field
  from user u
  join system s on u.system_id = s.id
  where s.name = 'Windows';
</code>```

Or if the same user can be in multiple systems:

```<code>select u.user_name, u.team, u.other_field
  from user u
  join user_system_xref usx on usx.user_id = u.id
  join system s on usx.system_id = s.id
  where s.name = 'Windows';
</code>```

Hmm... I see the "Object Oriented" tag in your post.  I guess I'll go just a little further and say that if you are using Hibernate, you might do something similar with a criteria query:

```<code>Crit<System> crit = Crit.create(System.class);
crit.add(Restrictions.eq("name", "Windows"));
System currSystem = crit.uniqueResult();

for (user : currSystem.getUsers()) {
    System.out.println(user.getName());
    System.out.println(user.getTeam().getName());
}
</code>```

Body:
Retrieve the ID from the database based on system name

All your other options involve duplicating the database data in your code.  Database and program design is usually a process of reducing data duplication, not increasing it.

If you were starting from scratch, and you didn't expect a new system very often and there were only a few systems, maybe you would start out with an enum.  When you got sick of recompiling and re-releasing the code every time you supported a new system, then you'd make a database table.  But since you already have a database table, I can't think of a reason not to use it.

I now need to explicitly reference the ID relating to Windows to query
  for user name, team etc.

Simple:

select u.user_name, u.team, u.other_field
  from user u
  join system s on u.system_id = s.id
  where s.name = 'Windows';

Or if the same user can be in multiple systems:

select u.user_name, u.team, u.other_field
  from user u
  join user_system_xref usx on usx.user_id = u.id
  join system s on usx.system_id = s.id
  where s.name = 'Windows';

Hmm... I see the "Object Oriented" tag in your post.  I guess I'll go just a little further and say that if you are using Hibernate, you might do something similar with a criteria query:

Crit<System> crit = Crit.create(System.class);
crit.add(Restrictions.eq("name", "Windows"));
System currSystem = crit.uniqueResult();

for (user : currSystem.getUsers()) {
    System.out.println(user.getName());
    System.out.println(user.getTeam().getName());
}


问:
Are dynamic languages at disadvantage for agile development?
From what I've read agile development often involves refactoring or reverse engineering code into diagrams. Of course there is much more than that, but if we consider the practices that rely on these two methods, are dynamically typed languages at disadvantage?

It seem staticly-typed languages would make refactoring and reverse engineering much easier.

Is Refactoring or (automated) reverse engineering hard if not impossible in dynamically typed languages?
What does real world projects tell about usage of dynamically typed languages for agile methodology?

答:
Dynamic languages are theoretically at a disadvantage, all else being equal, because they specify less about how the code works (what the constraints are), and therefore less of the refactoring can be done automatically, and problems that arise cannot be detected automatically as well.

But all else is not equal.  The most popular dynamic languages allow for highly compact yet comprehensible code, which generally makes development in them faster, and makes the logic (which may change in refactoring) easier to spot visually.  So though you might lose some of the relative advantage of working in a dynamic language, you might still come out ahead, especially if you were planning on doing your refactoring by hand anyway.

On the other hand, there exist statically typed languages with essentially the same advantages as dynamic languages (i.e. compact and comprehensible--with types mostly inferred, but very much there): Haskell is perhaps the leading example, but OCaML/F#, Scala, and others are in this category also.  Unfortunately, since they are less heavily used than the most popular statically typed languages, they don't have as extensive of toolsets for them (e.g. for refactoring).

So, as a bottom line, I think you'll do adequately with agile methodologies in most languages; I wouldn't say there's a clear winner right now as practice has not yet caught up with theory.


问:
High resolution graphical representation of the Earth's surface
I've got a library, which I inherited, which presents a zoomable representation of the Earth.  It's a Mercator projection and is constructed from triangles, the properties of which are stored in binary files.

The surface is built up, for any given view port, by drawing these triangles in an overlapping fashion to produce the image.  The definition of each triangle is the lat/long of the vertices.

It looks OK at low values of zoom but looks progressively more ragged as the user zooms in.  The view ports are primarily referenced though a rectangle of lat/long co-ordinates.

I'd like to replace it with a better quality approach.  The problem is, I don't know where to begin researching the options as I am not familiar either with the projections needed nor the graphics techniques used to render them.

For example, I imagine that I could acquire high resolution images, say Mercator projections although I'm open to anything, break them into tiles and somehow wrap them onto a graphical representation of a sphere.

I'm not asking for "how do I", more where should I begin to understand what might be involved and the techniques I will need to learn.

I am most grateful for any "Earth rendering 101" pointers folks might have.

答:
Sometimes the correct answer in programming is to not program.

It sounds like your question is in the "expert" level of knowledge for rendering, but neither your skills nor the existing documentation are there to back you in this quest.

As it sounds like you're running solo, I'm willing to guess that the topographical rendering isn't your business' core area.  Rather it's something drug along in order to represent what your core capability really is.

Others have solved this problem (topographical rendering) and sell the solution.  I'd recommend looking into them.  Google Earth is an example as is Microsoft Maps (or whatever it's called now).

I know it's odd on P.SE to recommend against coding, but I think this is a case where you are seriously out of your skill set.  You'll have a better solution more quickly by acquiring a 3rd party product instead.


问:
Does comparison operand order affect speed?
I notice that someone in my organization programs comparisons like:

```<code>if (100 == myVariable)
</code>```

rather than:

```<code>if (myVariable == 100)
</code>```

He claims the former is quicker in languages like C++.  I can't find any evidence.  We program in C#.

Is this true for any programming language?

答:
No, it is not "quicker": compilers will translate both expressions into the same code.

Some time ago the first pattern has been suggested to people coming to C from other languages where comparing objects required a single =. The idea was to protect them from making this mistake:

if (myVariable = 100)

This is legal, but it assigns 100 to myVariable instead of comparing myVariable to 100. If you make it a habit to put 100 ahead of myVariable, the compiler will trigger an error, because

```<code>if (100 = myVariable)
</code>```

is illegal.

Modern compilers issue warnings when they see an assignment in place of an equality check ==. You can silence the warning in cases when you do want to use an assignment inside an if by adding a second set of parentheses around your assignment expression.

Moreover, the construct is not useful in C# at all, because if (myVariable = 100) is not legal.

Body:
No, it is not "quicker": compilers will translate both expressions into the same code.

Some time ago the first pattern has been suggested to people coming to C from other languages where comparing objects required a single =. The idea was to protect them from making this mistake:

if (myVariable = 100)

This is legal, but it assigns 100 to myVariable instead of comparing myVariable to 100. If you make it a habit to put 100 ahead of myVariable, the compiler will trigger an error, because

if (100 = myVariable)

is illegal.

Modern compilers issue warnings when they see an assignment in place of an equality check ==. You can silence the warning in cases when you do want to use an assignment inside an if by adding a second set of parentheses around your assignment expression.

Moreover, the construct is not useful in C# at all, because if (myVariable = 100) is not legal.


答:
Short Answer: No, there is no difference. Both comparisons in example above have same effect.

It is translated to compiler with the same logic of comparison. Thus, they are identical in speed.

What makes difference is the order of operation. Thus, to avoid the operation order issues, it is a good practice to use brackets. In addition, you will get compiler warning in C# .NET if there is a wrong syntax used.

Title: Does comparison operand order affect speed?

Body:
I notice that someone in my organization programs comparisons like:

```<code>if (100 == myVariable)
</code>```

rather than:

```<code>if (myVariable == 100)
</code>```

He claims the former is quicker in languages like C++.  I can't find any evidence.  We program in C#.

Is this true for any programming language?


问:
Can the csv format be defined by a regex?
A colleague and I have recently argued over whether a pure regex is capable of fully encapsulating the csv format, such that it is capable of parsing all files with any given escape char, quote char, and separator char.

The regex need not be capable of changing these chars after creation, but it must not fail on any other edge case.

I have argued that this is impossible for just a tokenizer. The only regex that might be able to do this is a very complex PCRE style that moves beyond just tokenizing.

I am looking for something along the lines of:

... the csv format is a context free grammar and  as such, it is
  impossible to parse with regex alone ...

Or am I wrong? Is it possible to parse csv with just a POSIX regex?

For example, if both the escape char and the quote char are ", then these two lines are valid csv:

```<code>"""this is a test.""",""
"and he said,""What will be, will be."", to which I replied, ""Surely not!""","moving on to the next field here..."
</code>```

答: First define the grammar for your CSV (are the field delimiters escaped or encoded somehow if they appear in text?) and then it can be determined if it is parsable with regex. Grammar first: parser second: http://www.boyet.com/articles/csvparser.html It should be noted that this method uses a tokenizer - but I can't constuct a POSIX regex that would match all edge cases. If your usage of CSV formats is non-regular and context free ... then your answer is in your question. Good overview here: http://nikic.github.com/2012/06/15/The-true-power-of-regular-expressions.html </p>


答:
Simple answer - probably not.

The first problem is a lack of a standard.  While one may describe their csv in a way that is strictly defined, one cannot expect to get strictly defined csv files.  "Be conservative in what you do, be liberal in what you accept from others" -Jon Postal

Assuming that one does have a standardesque that is acceptable, there is the question of escape characters and if these need to be balanced.

A string in many csv formats is defined as string value 1,string value 2.  However, if that string contains a comma it is now "string, value 1",string value 2.  If it contains a quote it becomes "string, ""value 1""",string value 2.

At this point I believe it is impossible.  The problem being you need to determine how many quotes you have read and if a comma is inside or outside of the double quoted mode of the value.  Balancing parentheses is an impossible regex problem.  Some extended regular expression engines (PCRE) can deal with it, but it isn't a regular expression then.

You might find https://stackoverflow.com/questions/8629763/csv-parsing-with-a-context-free-grammar useful.

Amended:

I have been looking at formats for escape characters and haven't found any that need arbitrary counting - so that is probably not the issue.

However, there are issues of what is the escape character and record delimiter (to start with).  http://www.csvreader.com/csv_format.php is a good read on the different formats in the wild.

The rules for the quoted string (if it is a single quoted string or a double quoted string) differ.

'This, is a value' vs "This, is a value"

The rules for escape characters

"This ""is a value""" vs "This \"is a value\""

The handling of embedded record delimiter ({rd})

(raw embeded) "This {rd}is a value" vs (escaped) "This \{rd}is a value" vs (translated)"This {0x1C}is a value"

The key thing here is that it is possible to have a string that will always have multiple valid interpretations.

The related question (for edge cases) "is it possible to have a invalid string that is accepted?"

I still strongly doubt that there is a regular expression that can match every valid CSV that is created by some application and reject every csv that cannot be parsed.

Title: Can the csv format be defined by a regex?

Body:
A colleague and I have recently argued over whether a pure regex is capable of fully encapsulating the csv format, such that it is capable of parsing all files with any given escape char, quote char, and separator char.

The regex need not be capable of changing these chars after creation, but it must not fail on any other edge case.

I have argued that this is impossible for just a tokenizer. The only regex that might be able to do this is a very complex PCRE style that moves beyond just tokenizing.

I am looking for something along the lines of:

... the csv format is a context free grammar and  as such, it is
  impossible to parse with regex alone ...

Or am I wrong? Is it possible to parse csv with just a POSIX regex?

For example, if both the escape char and the quote char are ", then these two lines are valid csv:

```<code>"""this is a test.""",""
"and he said,""What will be, will be."", to which I replied, ""Surely not!""","moving on to the next field here..."
</code>```


答: If you are passing objects around simply because it's needed in a remote area of your code, using the inversion of control and dependency injection design patterns along with optionally an appropriate IoC container can nicely solve problems regarding carrying object instances around.  I've used it on a medium-sized project and would never again consider writing a large piece of server code without using it.</p>


答:
Regex can parse any regular language, and cannot parse fancy things like recursive grammars. But CSV seems to be pretty regular, so parseable with a regex.

Let's work from definition: allowed are sequence, choice form alternatives (|), and repetition (Kleene star, the *).

An unquoted value is regular: [^,]* # any char but comma

A quoted value is regular: "([^\"]|\\\\|\\")*" # sequence of anything but quote " or escaped quote \" or escaped escape \\

Some forms may include escaping quotes with quotes, which adds a variant ("")*" to the expression above.

An allowed value is regular: <unquoted-value>|<quoted-value>

A single CSV line is regular: <value>(,<value>)*

A sequence of lines separated by \n is also obviously regular.

I did not meticulously test each of these expressions, and never defined catch groups. I also glossed over some technicalities, like the variants of characters which can be used instead of ,, ", or line separators: these do not break the regularity, you just get several slightly different languages.

If you can spot a problem in this proof, please comment! :)

But despite this, practical parsing of CSV files by pure regular expressions may be problematic. You need to know which of the variants is being fed to the parser, and there's no standard for it. You can try several parsers against each line until one succeeds, or somehow divinate the format form comments. But this may require means other than regular expressions to do efficiently, or at all.


答: This problem can be solved with dynamically scoped variables, if your language has them, or thread-local storage. These mechanisms let us associate some custom variables with an activation chain or thread of control, so that we don't have to pass these values around into code that has nothing to do with them just so that they can be communicated down to some other code which does need them. </p>


问:
When is a Use Case layer needed?
In his blog post The Clean Architecture Uncle Bob suggests a 4-layer architecture. I understand the separation between business rules, interfaces and infrastructure, but I wonder if/when it's necessary to have separate layers for domain objects and use cases. What added value will it bring, compared to just having the uses cases as "domain services" in the domain layer?

The only useful info I've found on the web about a use case layer is an article by Martin Fowler, who seems to contradict Uncle Bob about its necessity:

At some point I may run into the problems, and then I'll make a Use
  Case Controller - but only then. And even when I do that I rarely
  consider the Use Case Controllers to occupy a separate layer in the
  system architecture.

Edit:

I stumbled upon a video of Uncle Bob's Architecture: The Lost Years keynote, in which he explains this architecture in depth. Very informative.

答:
I disagree with Uncle Bob's use of the term "use case" but I understand what he's getting at.  I don't really want to quibble over the semantics of the term in any case.

For the sake of this question, use cases are application specific business rules.

Your question is really "when are separate layers needed for both enterprise business rules and application specific business rules?"  And the quick answer is you need them when your application grows large enough to justify it.

If there are a small number of rules from either set, then it's just as easy to keep the implementation of those rules within a single application layer.  If there are lots of rules for both sets, then you'll want to break them out to specific layers.

Uncle Bob lays out a rule that the inner circles shouldn't know of the outer circles in his architectural diagram.  And that's ultimately the answer to your question.  As the rules evolve and have clear delineation from the others then you'll need to isolate them out to separate layers.

Title: When is a Use Case layer needed?


问:
Using a texture as an integer array (OpenGL 3.3, shader version 3.3)
I'm trying to have something like an integer array uniform for my fragment shader (I only need read access). Since it's a fairly large chunk of data (not so large that uploading it in every frame would be impossible, but enough to make me want to rather not do it). Essentially I want to just pass it a uniform telling the shader where this "array" is. I believe I can use a 1D texture for this, but I don't know how (actually, I don't know how to do many things because I just can't seem to find a reference for GLSL 3.3, I only ever find references for the C API).

This sounds like a rather basic question and I'm sure it's been answered already somewhere, but I keep searching and can't quite find what I'm looking for.

答: Have a look at this OpenGL tutorial.  The chapter on textures explains how to do exactly what you're looking for--deal with a texture as specifically an array of numeric values instead of as graphical data--but the whole thing is worth reading.</p>


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
I use the first syntax, almost without exception. Because it cannot be misinterpreted.

"Don't make me think" doesn't just apply to user-interfaces, y'all ;-)


问:
Difference between Windows and Linux development environments?
I have an interview coming up soon for a Business Analyst position and the recruiter mentioned some feedback from a prior candidate that was interviewed who said the interviewers asked him what the difference between a Windows and Linux development environment was.  Are there some high level things I need to be aware of from a business point of view when working with a development team or designing an application on Windows vs Linux?</p>

答:
Usually the software stack for Linux is Open Source, made of LGPL/GPL licenses. You may want to read up on them to see if there's any implications in it for you. The discussion of open source is long, tedious, and out of scope for this question so I won't go into it. In Windows environments, open source plays a much smaller role and Microsoft's is the go-to solution for many things, providing a complete stack for pretty much all kinds of development.

The development environment itself is fairly different (in terms of IDEs, tools, how things work), and a lot of the developers have strong preferences in terms which environment they like to work with. People have been known to be deeply religious about this sort of stuff, but if you're talking about things like web applications then similar results can be achieved with either.

From a business perspective you typically want to go with whatever your team is most familiar with.

EDIT

I know that Business Analyst can be a fairly overloaded term, and you haven't specified exactly what the position you are applying for entails. Perhaps it is more on the technical side (in my current place of work BAs write Python scripts and know more about database schemas/relationships then devs). If this is the case then you might have to know about Linux (UNIX) in general, and I suggest downloading a distro (Ubuntu, OpenSUSE, Fedora) and poking around as well as doing some reading.


答:
Most of the differences between Windows and Linux should be transparent to you as a business analyst. The major things you should keep in mind are compatibility issues with products someone might have heard of at some conference or something and they want it added to your app. Also look and feel issues can crop up, you can generally tell when Linux things get ported to Windows and vice versa. Otherwise the differences are largely technical and should be able to be handled by the development team.

The last thing to keep in mind is that Linux and Windows people behave differently and have different thought processes, looking to Microsoft first for solutions vs looking for open source solutions and customizing from there.

Title: Difference between Windows and Linux development environments?

Body: I have an interview coming up soon for a Business Analyst position and the recruiter mentioned some feedback from a prior candidate that was interviewed who said the interviewers asked him what the difference between a Windows and Linux development environment was.  Are there some high level things I need to be aware of from a business point of view when working with a development team or designing an application on Windows vs Linux?</p>


答:
Short Answer: Difference is in ecosystems they represent and client base that each refer.

I am pretty sure you have information about Windows and may be about its development world, that is mostly windows operating system with .NET framework and iconic products like MS office, outlook, etc. This world mainly tight to licencing.

While Linux (Unix )world is complete opposite to licencing with many open-source products like Open Office, Java, etc. Thus, Unix world developers always religiously oppose the Microsoft world (windows) as a corporate greed, where each product should be paid first.

However, there were drastic changes in Microsoft software development approach in terms of going open-source. Thanks to GitHub and similar software project hosting websites and community of developers that use and contribute to it. For example, ASP.NET MVC is an open source framework, NuGet packages are free as well.

Thus, main difference is in ecosystem that they do represent. However, in web development world these differences are insignificant.

From business analyst perspective it is more about the "client base" that each ecosystem serves.


问:
Collaboration between client, web designer, and web developer
I am primarily a Web Developer (back end programming) - but intend to offer a complete service to my clients, from concept, to brand design, photoshop mock-ups and everything else in between. I'm aware that it's a good idea to outsource this design aspect of the project to someone that I trust. My question is more about the process:

I imagine that in order for the designer to really grasp what the client wants to create, they would need some sort of interaction. Therefore, does anyone know if it is common to bring both parties into a 3 way discussion? Or is it more common to get all of the info from the client, and then pass it onto the designer, and act as a back and forth middleman? Afterall, I am the designer's client.

Any insight into this would be great

答:
I would think that you would act as a middle man or more like a project manager.  you would get the information from the clients on what they want and then pass that information on to the designer.  this way you know what is going on so that either you can tell him what you need for coding or you know what he is doing with it for when you code.  this is very necessary for functionality of the application.  if you have worked together a lot, then you would have a better understanding of what the other needs to create a good product and could determine, per client, whether it would be beneficial to have both of you there with the client.

you should have several iterations as well, so if need be you can bring the designer to one of the iteration meetings, which is probably what I would do in the given scenario.


问:
Git commit messages with nvie branching model
This Git branching model recommends branching for all development efforts and merging when complete:

Branch

Develop

Merge when complete

I'm wondering how this works in practice, given that performing a merge off this model will simply add a commit to the develop with whatever commit message happened to be the last one in line. Do people using this model do an interactive rebase on the feature branch before committing? If not, how do you ensure that the commits make sense on the main branch?

答:
I've been using the branching model you mentioned for a while and this is the flow I've settled on:

Create feature branch.

Do work. Possibly several commits happen in the feature branch depending on the feature.

When feature work is complete, do interactive rebase, squashing all the feature branch commits into one commit.

Merge feature branch back into dev branch.

Delete feature branch.

The important step here is number three. You need to write a really good commit message when you rebase. It should have a single line at the top that gives a good overview of the commit followed by an empty line, then as many lines as you need to describe the commit in detail. For example:

```<code>Adds Feature Name (with reference to bug tracker/project management tool ticket)

This is a paragraph that describes this commit in detail. I usually use it to
describe decisions I've made, why I made them and potential limitations of the
implementation. I might follow this up with some bullet points:

- Detail 1
- Detail 2
- Detail 3
</code>```

This way when you run git log --oneline it's clear from the first line what's going on in this particular commit. If you then run git log or git show {sha} you can see the full commit message.

Of course you can make use of gitk and git log --graph to get a graphical representation of all your commits.

Body:
I've been using the branching model you mentioned for a while and this is the flow I've settled on:

Create feature branch.

Do work. Possibly several commits happen in the feature branch depending on the feature.

When feature work is complete, do interactive rebase, squashing all the feature branch commits into one commit.

Merge feature branch back into dev branch.

Delete feature branch.

The important step here is number three. You need to write a really good commit message when you rebase. It should have a single line at the top that gives a good overview of the commit followed by an empty line, then as many lines as you need to describe the commit in detail. For example:

Adds Feature Name (with reference to bug tracker/project management tool ticket)

This is a paragraph that describes this commit in detail. I usually use it to
describe decisions I've made, why I made them and potential limitations of the
implementation. I might follow this up with some bullet points:

- Detail 1
- Detail 2
- Detail 3

This way when you run git log --oneline it's clear from the first line what's going on in this particular commit. If you then run git log or git show {sha} you can see the full commit message.

Of course you can make use of gitk and git log --graph to get a graphical representation of all your commits.


问:
Is it bad practice to pass instances through several layers?
In my program design, I often come to the point where I have to pass object instances through several classes. For example, if I have a controller that loads an audio file, and then passes it to a player, and the player passes it to the playerRunnable, which passes it again somewhere else etc. It looks kind of bad, but I don´t know how to avoid it. Or is it OK to do this?

EDIT: Maybe the player example is not the best because I could load the file later, but in other cases that does not work.

答:
What you are describing is a called a Chain Of Responsibility design pattern.
 Apple uses this pattern for their event-handling system, for what it's worth.</p>


答:
I've been through this same problem recently and adopted the following solution:

Data access methods should get data only from a single resource (e.g., database table), and if the process needs related objects appended to the main object it should call for the method responsible for those respective objects.

This way if you need an asset with it's approvers you should create a facade method wich join the objects.

Example:

```<code>public Class AssetFacade {

   public AssetDto getAssetWithQuestionsByAssetId(int assetId) {

      AssetDto asset = AssetDao.getAssetById(assetId);
      List<QuestionDto> questions = AssetDao.getQuestionsByAssetId(assetId);
      asset.setQuestions(questions);

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

Body:
I've been through this same problem recently and adopted the following solution:

Data access methods should get data only from a single resource (e.g., database table), and if the process needs related objects appended to the main object it should call for the method responsible for those respective objects.

This way if you need an asset with it's approvers you should create a facade method wich join the objects.

Example:

public Class AssetFacade {

   public AssetDto getAssetWithQuestionsByAssetId(int assetId) {

      AssetDto asset = AssetDao.getAssetById(assetId);
      List<QuestionDto> questions = AssetDao.getQuestionsByAssetId(assetId);
      asset.setQuestions(questions);

      return asset;
   };
 }


问:
TDD - Outside In vs Inside Out
What is the difference between building an application Outside In vs building it Inside Out using TDD?

These are the books I read about TDD and unit testing:

Test Driven Development: By Example

Test-Driven Development: A Practical Guide: A Practical Guide

Real-World Solutions for Developing High-Quality PHP Frameworks and Applications

Test-Driven Development in Microsoft .NET

xUnit Test Patterns: Refactoring Test Code

The Art of Unit Testing: With Examples in .Net

Growing Object-Oriented Software, Guided by Tests--->This one was really hard to understand since JAVA isn't my primary language :)

Almost all of them explained TDD basics and unit testing in general, but with little mention of the different ways the application can be constructed.

Another thing I noticed is that most of these books (if not all) ignore the design phase when writing the application. They focus more on writing the test cases quickly and letting the design emerge by itself.

However, I came across a paragraph in xUnit Test Patterns that discussed the ways people approach TDD. There are 2 schools out there Outside In vs Inside Out.

Sadly the book doesn't elaborate more on this point. I wish to know what is the main difference between these 2 cases.

When should I use each one of them?

To a TDD beginner which one is easier to grasp?

What is the drawbacks of each method?

Is there any materials out there that discuss this topic specifically?

答:
As I see it, the concept of Outside-in development really spreads on 2 levels. Gerard Meszaros briefly describes them as "outside-in design" and "outside-in/inside-out coding".

The first level is an organizational and process level. Outside-in design is meant as opposed to top-down (waterfall/taylorist) and bottom-up. With an outside-in approach, we focus on the end user's perspective. We start with story tests, ATDD or BDD tests and go "inward" inferring technical tests and code. So outside-in design is typically what you would do in an Agile context. Dan North has a great talk about BDD, top-down, bottom-up and outside-in approaches.

The second level is technical and has to do with applicative layers. Outside-in coding basically means starting from the UI and going inwards to the central layer (usually the business/domain layer). It's meant as opposed to inside-out coding which is starting from the central layer and coding the external layers last.

So you could have outside-in design with either outside-in coding or inside-out coding.

Where I disagree with Meszaros is when he associates inside-out coding with integration testing, arguing that in an inside-out context "we don't actually test the outer software in isolation of the inner software". But I believe nothing prevents you to do so. You can perfectly choose to test your outer layer objects by mocking out the inner layer objects even if the production code for those already exists. You just have to add interfaces and mocks on top of the existing concrete objects instead of writing the interfaces, mocking them and then creating the implementations later as you would do with outside-in coding.

In other words, mockist or classicist style TDD is IMO an orthogonal concern to outside-in/inside out coding. You can perfectly use a mockist style together with an inside out approach.
The reason behind this is that mockist/classicist style is about code dependencies while outside-in/inside-out coding is about applicative layers.

Another important thing is that dependencies aren't only across layers, they also exist between objects in the same layer. For instance, you might want to start with one object in your central business layer (inside-out approach) and use mocks to isolate your object from other business layer objects it talks to. This happens a lot with IoC - the abstractions your object depends upon are often declared in the same layer, but concrete implementations are in a different layer.

Robert "Uncle Bob" Martin briefly mentions inside-out coding and how it doesn't necessarily conflict with a decoupled architecture in his post "Clean Architecture".

Title: TDD - Outside In vs Inside Out


问:
Where should "display functions" live in an MVC web app?
I'm using the Yii Framework which is an MVC php framework that is pretty similar to your standard web-based MVC framework.  I want to display the related data from a many-to-many table as a list of strings in my view.

Assuming a table schema like:

```<code>tag { id, name }
post { id, title, content, date }
post_tag { post_id, tag_id }
</code>```

A post will display like:

```<code>Date: 9/27/2012
Title: Some Title
Content: blah blah blah...
Tags: Smart Funny Cool Informative
</code>```

I can achieve this by doing something like this in my Post view:

```<code><?php
  echo join(' ',
           array_map(function($tag) { return $tag->name; }, $model->tags));
?>
</code>```

(where $model->tags is an array of Tag objects associated with my model)

My questions are:

Is this amount of code/logic okay in the view? (Personally I think I'd rather just reference a property or call a single function.)

If not, where should this code live? In the model? the controller? a helper?

Potentially I may want to use in in other views as well.  Ultimately I think its purely a display issue which would make me think it should be in the view, but then I have to repeat the code in any view I want to use it in.

答:
Is this amount of code/logic okay in the view? (Personally I think I'd rather just reference a property or call a single function.)

For clean separation of concerns in MVC design, you better move all calculation from your views to controller or service layer. Thus, code should live in your controller, assigned to a new property of your viewmodel or dto.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答:
I used to work for IBM where COBOL and PL/I code was written every day. Also from big companies relying on IBMs mainframes like many banks which require thousands of transactions per second those languages are still heavilly used.

If you don't want to work in a place like that (That's why I just worked there for 6 months) then don't even think of learning those languages.

Title: Is COBOL still worth learning?


问:
Most efficient Implementation a Tree in C++
I need to write a tree where each element may have any number of child elements, and because of this each branch of the tree may have any length.

The tree is only going to receive elements at first and then it is going to use exclusively for iterating though it's branches in no specific order.

The tree will have several million elements and must be fast but also memory efficient.

My plan makes a node class to store the elements and the pointers to its children.  When the tree is fully constructed, it would be transformed it to an array or something faster and if possible, loaded to the processor's cache.

Construction and the search on the tree are two different problems.  Can I focus on how to solve each problem on the best way individually?  The construction of has to be as fast as possible but it can use memory as it pleases.  Then the transformation into a format that give us speed when iterating the tree's branches. This should preferably be an array to avoid going back and forth from RAM to cache in each element of the tree.

So the real question is which is the structure to implement a tree to maximize insert speed, how can I transform it to a structure that gives me the best speed and memory?

答:
A natural way to implement an updateable tree with arbitrary numbers of children per node is to reinterpret a binary tree such that the "left hand" link points to the node's first child, and the "right hand" link points to the next child of the same parent.  This takes two links per node, and requires linear list traversal to locate a particular child.  However, if the order of the children doesn't matter, you can simply insert each child at the head of the child list.

You can construct a read-only tree with only one link per node, by concatenating all children of a given node into a sub-vector, and dropping the right-hand link in favor of iteration.  You will need to include either a boolean last_child flag or a child_count field as part of your read-only node structure; note that the child_count version will permit random access of child lists.

If your read-only queries frequently iterate through long child lists, this may dramatically improve your cache usage.  Alternately, if your read-only queries frequently iterate in a depth-first manner, it may be more efficient to drop the left-hand link in favor of iteration, by concatenating all first-child chains into a sub-vector.

In either case, you can use an STL vector<> to do memory-management for the read-only tree -- by doing a traversal (in the appropriate order) of your updateable tree, and using push_back() to append the read-only version of each tree node, in order.  Remember that you will need to use indices rather than pointers for your links, as pushing an element may reallocate the vector<>.

Finally, minimizing the size of your read-only node structure can improve your performance.  If your read-only node includes a link to the original datastructure, you can profitably strip out any data not needed during a query's traversal but only used when the query finds its target.  (Come to think of it, the updateable tree might also benefit from this.)


问:
Is a scrum sprint backlog ordered?
Currently, Wikipedia Scrum Article defines "Sprint Backlog" as:

A prioritized list of tasks to be completed during the sprint.

It is my understanding that the "Product Backlog" is a prioritized list but that the "Sprint Backlog" does not have an order. I am looking for a definitive reference for the answer.

答:
The scrum alliance / scrum foundation documents are not absolutely definitive on this however this is because it is implied all over the place.  Logically the sprint backlog has to be ordered.

It is a more detailed sub set of the product backlog which is ordered and you plan by working through the product backlog in order of priority.  Why wouldn't you work on the highest priority?

Minimizing work in progress and swarming stories is encouraged because you want to maximize the number of complete stories, not have several half finished ones at the end of the sprint as those don't meet the definition of done or have any business value.

Given the ethos of Scrum (prioritization, maximising business value, increasingly x-functional teams) it just wouldn't make sense for this to be unordered.

Title: Is a scrum sprint backlog ordered?


问:
What is the precise definition of programming paradigm?
Wikipedia defines programming paradigm thus:

a fundamental style of computer programming

which is echoed in the descriptive text of the paradigms tag on this site.

I find this a disappointing definition. Anyone who knows the words programming and paradigm could do about that well without knowing anything else about it. There are many styles of computer programming at many level of abstraction; within any given programming paradigm, multiple styles are possible. For example, Bob Martin says in Clean Code (13),

Consider this book a description of the Object Mentor School of Clean Code. The techniques and teachings within are the way that we practice our art. We are willing to claim that if you follow these teachings, you will enjoy the benefits that we have enjoyed, and you will learn to write code that is clean and professional. But don't make the mistake of thinking that we are somehow "right" in any absolute sense.

Thus Bob Martin is not claiming to have the correct style of Object-Oriented programming, even though he, if anyone, might have some claim to doing so. But even within his school of programming, we might have different styles of formatting the code (K&R, etc). There are many styles of programming at many levels.

So how can we define programming paradigm rigorously, to distinguish it from other categories of programming styles? Fundamental is somewhat helpful, but not specific. How can we define the phrase in a way that will communicate more than the separate meanings of each of the two words—in other words, how can we define it in a way that will provide additional meaning for someone who speaks English but isn't familiar with a variety of paradigms?

答:
Very good explanations of programming paradigms and the programming concepts from which those paradigms are built are found in Peter van Roy's works. Especially in the book Concepts, Techniques, and Models of Computer Programming by Peter Van Roy and Seif Haridi. (Here's the companion wiki.) CTM (as it is colloquially known) uses the multi-paradigm Distributed Oz programming language to introduce all the major programming paradigms.

Peter van Roy also made this amazing poster that shows the 34 major paradigms and their relations and positions on various axis. The poster is basically an incredibly compressed version of CTM. A more thorough explanation of that poster is contained in the article Programming Paradigms for Dummies: What Every Programmer Should Know which appeared as a chapter in the book New Computational Paradigms for Computer Music, edited by G. Assayag and A. Gerzso. It explains for example very concisely and easily understandable, what a programming paradigm actually is, what a programming concept is, and how the two are related.


答:
I'm primarily a web UI dev but it sounds to me like your intuitive discomfort might be less about the instance pass-through and more about the fact that you're going a bit procedural with that controller. Should your controller be sweating all these details? Why does it even reference more than one other object's name for getting audio played?

In OOP design, I tend to think in terms of what's evergreen and what's more likely to be subject to change. The subject to change stuff is what you're going to want to tend to put in your larger object boxes so you can maintain consistent interfaces even as players change or new options are added. Or you find yourself wanting to swap audio objects or components therein wholesale.

In this case, your controller needs to identify that there's a need to play an audio file and then have a consistent/evergreen way of getting it played. The audio player stuff on the other hand could easily change as technology and platforms get altered or new choices are added. All of those details should sit underneath an interface of a larger composite object, IMO, and you shouldn't have to rewrite your controller when the details of how audio gets played change. Then when you pass an object instance with the details like file location into the larger object all that swapping around is done in the interior of an appropriate context where someone is less likely to do something silly with it.

So in this case I don't think it's that object instance getting tossed around that might be bugging you. It's that Captain Picard is running down to the engine room to turn the warp core on, running back up to the bridge to plot the coordinates, and then hitting the "punch-it" button after turning the shields on rather than simply saying "Take us to planet X at Warp 9. Make it so." and letting his crew sort out the details. Because when he handles it that way, he can captain any ship in the fleet without knowing the layout of every ship and how everything works. And that's ultimately the biggest OOP design win to shoot for, IMO.


问:
Java - What methods to put in an interface and what to keep out
I'm designing a file handler interface:

```<code>public interface FileHandler
{
    public void openFileHandler(String fileName);
    public void closeFileHandler();

    public String readLine();
    public String [] parseLine(String line);
    public String [] checkLine(String line[]);

    public void incrementLineCount();
    public void incrementLineSuccessCount();
    public void incrementLineErrorCount();

    public int getLineCount();
    public int getLineSuccessCount();
    public int getLineErrorCount();
}
</code>```

It is soon apparent to me that these methods can't be made private. I don't want incrementLineCount to be public.

What is proper way to design an interface like this?

答:
An interface specifies behavior, not specific implementation details.

You should specify the operations you want anything that implements your interface to support.    One way of determining that is asking "How will consumers use my interface; what is the contract I am specifying?"

Leave the details (e.g. the private methods) up to the implementations. That's the point of interfaces -- you can have different implementations that behave in different ways, e.g. the difference between reading a file off disk and reading a file off the cloud....

OwnerDisplayName: lewicki

OwnerDisplayName: hvgotcodes


答:
Interfaces should be designed by keeping in mind what outside objects will need to call on classes that implement the specific interface.

This is just what the class should be able to do from the outside. For everything else you can use abstract classes with protected methods (so you will have the same commodity to force implementation in subclasses but without being forced to let them public).

Something like:

```<code>interface FileHandler {
  public void openFileHandler(String fileName);
  public void closeFileHandler();
}

abstract class AbstractFileHandler implements FileHandler {
  ...
  protected abstract void incrementLineCount();
  protected abstract void incrementLineSuccessCount();
  protected abstract void incrementLineErrorCount();
}

class ConcreteFileHandler extends AbstractFileHandler {
  ...
}
</code>```

If you don't need to have a common ancestor just declare the private methods in your concrete class and you are done.

Title: Java - What methods to put in an interface and what to keep out

Body:
I'm designing a file handler interface:

```<code>public interface FileHandler
{
    public void openFileHandler(String fileName);
    public void closeFileHandler();

    public String readLine();
    public String [] parseLine(String line);
    public String [] checkLine(String line[]);

    public void incrementLineCount();
    public void incrementLineSuccessCount();
    public void incrementLineErrorCount();

    public int getLineCount();
    public int getLineSuccessCount();
    public int getLineErrorCount();
}
</code>```

It is soon apparent to me that these methods can't be made private. I don't want incrementLineCount to be public.

What is proper way to design an interface like this?

Body:
Interfaces should be designed by keeping in mind what outside objects will need to call on classes that implement the specific interface.

This is just what the class should be able to do from the outside. For everything else you can use abstract classes with protected methods (so you will have the same commodity to force implementation in subclasses but without being forced to let them public).

Something like:

interface FileHandler {
  public void openFileHandler(String fileName);
  public void closeFileHandler();
}

abstract class AbstractFileHandler implements FileHandler {
  ...
  protected abstract void incrementLineCount();
  protected abstract void incrementLineSuccessCount();
  protected abstract void incrementLineErrorCount();
}

class ConcreteFileHandler extends AbstractFileHandler {
  ...
}

If you don't need to have a common ancestor just declare the private methods in your concrete class and you are done.

OwnerDisplayName: Jack


答:
So how can we define programming paradigm rigorously, to distinguish it from other categories of programming styles?

You don't.

Program design is the side of programming that is more craftsmanship than engineering. People don't go around trying to rigorously define painting's Cubism, or Gothic architecture. They're terms that people apply to label categorizations. They're not evolved out of some natural truth. If a building uses pointed archways, then it better fits into the Gothic category.

Likewise, if I tend to use pure methods and immutable data, the design has a Functional slant. The concepts can be mingled and adapted, and evolve over time. It's rare when modern programs aren't a shade of grey with traits of different paradigms.

Title: What is the precise definition of programming paradigm?

Body:
Wikipedia defines programming paradigm thus:

a fundamental style of computer programming

which is echoed in the descriptive text of the paradigms tag on this site.

I find this a disappointing definition. Anyone who knows the words programming and paradigm could do about that well without knowing anything else about it. There are many styles of computer programming at many level of abstraction; within any given programming paradigm, multiple styles are possible. For example, Bob Martin says in Clean Code (13),

Consider this book a description of the Object Mentor School of Clean Code. The techniques and teachings within are the way that we practice our art. We are willing to claim that if you follow these teachings, you will enjoy the benefits that we have enjoyed, and you will learn to write code that is clean and professional. But don't make the mistake of thinking that we are somehow "right" in any absolute sense.

Thus Bob Martin is not claiming to have the correct style of Object-Oriented programming, even though he, if anyone, might have some claim to doing so. But even within his school of programming, we might have different styles of formatting the code (K&R, etc). There are many styles of programming at many levels.

So how can we define programming paradigm rigorously, to distinguish it from other categories of programming styles? Fundamental is somewhat helpful, but not specific. How can we define the phrase in a way that will communicate more than the separate meanings of each of the two words—in other words, how can we define it in a way that will provide additional meaning for someone who speaks English but isn't familiar with a variety of paradigms?


问:
2 Servers 1 Database - Can I use Redis?
Ok I have a couple of questions here. First let me give you some background information. I'm starting a project where I have a node.js server running my application and my website running on another normal server. My application will allow multiple users simultaneous connections and updates to the database so Redis seemed like a good fit there because of its speed and atomic functions.

For someone to access my application they have to login with an account. To get an account, they have to signup for one through my website. So my website needs a database, but its not important to have a database like Redis here because it doesn't need it. Which leads me to my first question:

1. Can Redis even be used without node.js?

It seems like it would be convenient if both of my servers were using the same database to keep track of information. In some cases, they will keep track of the same information (as in user information) and in other cases, they will be keeping track of separate information. So even if the website wouldn't be taking full advantage of all that Redis has to offer it seems like it would be more convenient. So assuming Redis could be used in this situation that leads to my next question:

2. Since Redis is linked with JavaScript, how would I handle the security from my website users?

What would be stopping my website users from opening firebug or chrome's inspector and making changes to the database? Maybe if I designed my site with the layout like this: apply.php->update.php->home.php. Where after they submitted their form it would redirect them to the update page where the JavaScript would run and then redirect them after the database updated to the home page. I don't really know I'm just taking shots in the dark at this point. :)

Maybe a better alternative would be to have my node.js application access its own Redis database and also have access to another MySQL database that my website also has access to. Or maybe there is another database that would be better suited for this situation other than Redis. Anyways any direction on this matter would be greatly appreciated. :)

答:
What would be stopping my website users from opening firebug or
  chrome's inspector and making changes to the database?

If this is possible, you've got some serious redesigning to do.  All your authentication should be on the server end of things.  Your node server should be validating the request before it takes any action.  End users fiddling with javascript should not be able to perform any action they couldnt already do in the web interface.

This has absolutely nothing to do with the database being used.  I'd advise you not to even worry about selecting a DB until you've worked out the above.

Addendum

In response to Aust's question below.

But if I wrote my code to have the website connect to Redis, then
  that's when I would run into security issues, yes?

Yes, thats a huge security problem.  You shouldnt be writing directly to the database from the web browser.  For starters, doing so requires that you'd give out database user/pass to every web client.  Rather, have your javascript code talk to another app on your server, and have that app interact with the database.  Your intermediary app (aka, app server, web service, middle tier, etc) should authenticate the user and then only allow actions that user is allowed to do.  The web client should have no idea that a database even exists.

Title: 2 Servers 1 Database - Can I use Redis?


问:
How to unit test image processing code?
I'm working in image processing (mainly OCR) and I wonder how I should integrate unit tests in my development.

I'm already using unit tests for more "common" type of code but when dealing with image processing code I'm not sure how to deal with it. This kind of code always need some image data input/output and mocking this is not obvious. For now I'm mostly doing integration tests but they take a while to run and I would like some ideas on how to break down this kind of code into unit tests so that I can run them more quickly.

Edit:
Analyzing a character can go through many steps involving multiple rotation, scaling and morphological operations. These steps change often as the algorithm is being developed. Thus the input and expected output can evolve a lot while testing. Each character can be 100x100 pixels so hardcoding them in the code or working with generated data is out of question.

答:
I work with video recording/analytics/streaming software and we faced a very similar problem.  Below was our solution, not sure how it'll work out long-term but for now it seems to work.

Save input/output images as resources in your unit test project. Then have unit test verify that when a specific input is given, that specific output is produced.

9/10 times when you refactor the code and add other functionality, you would expect the behavior of your image handling routines not to change, so if all of a sudden unit tests start failing, it's likely due to an error.

On the other hand, if you make changes in the actual algorithm, that will also result in unit test failure. In this case, you would have to manually/visually verify that the results are correct and if they look good, then update the image resources to make the unit test pass again.

In our project, we ended up developing "fake" (or mock if you will) video sources, that can feed us data both for input and output. But the data itself is not fake, it was actually captured using helper data recording classes from a running system when we ran manual tests and verified that everything was working.

Title: How to unit test image processing code?


问:
Does the Head(start) pointer of Doubly Linked list points previously to the tail(last) node
I have one question in my mind that in case of circular doubly linked list the head pointer of the doubly linked list also logically point to the next pointer of the tail node of the linked list and tail's next pointer also point to the previous pointer of head.

Please Answer me this question I am a bit confused.

答:
Assume you have a circular doubly linked list with three nodes at position 1, 2 and 3:

```<code>[1] next->2 prev->3
[2] next->3 prev->1
[3] next->1 prev->2
</code>```

In some sense there is no "head" and "tail" in a circular doubly linked list. Though you will have a pointer outside as an entry point to access the list like head->1, which would be identical to 3:next->1.

So the heads prev points to the "tail"

The tails next points to the "head"

Body:
Assume you have a circular doubly linked list with three nodes at position 1, 2 and 3:

[1] next->2 prev->3
[2] next->3 prev->1
[3] next->1 prev->2

In some sense there is no "head" and "tail" in a circular doubly linked list. Though you will have a pointer outside as an entry point to access the list like head->1, which would be identical to 3:next->1.

So the heads prev points to the "tail"

The tails next points to the "head"


答:
It depends.

Is it a circular or linear list?

If it's a circular list then there is no "head" or "tail" as each element's next and prev pointers will be set. You can start traversing the list anywhere and have to remember where you started so you know when to stop.

If it's a linear list then the prev pointer of the head element will be null and the next pointer of the tail element will be null. You use this information to know when to stop.

Title: Does the Head(start) pointer of Doubly Linked list points previously to the tail(last) node

Body:
I have one question in my mind that in case of circular doubly linked list the head pointer of the doubly linked list also logically point to the next pointer of the tail node of the linked list and tail's next pointer also point to the previous pointer of head.

Please Answer me this question I am a bit confused.


问:
Introduce unit testing when codebase is already available

Possible Duplicate:

  Best practices for retrofitting legacy code with automated tests

I've been working on a project in Flex for three years now without unit testing. The simple reason for that is the fact that I just didn't realize the importance of unit testing when being at the beginning of studies at university. Now my attitude towards testing changed completely and therefore I want to introduce it to the existing project (about 20000LOC).

In order to do it, there are two approaches to choose from:

1) Discard the existing codebase and start from scratch with TDD

2) Write the tests and try to make them pass by changing the existing code

Well, I would appreciate not having to write everything from scratch but I think by doing this, the design would be much better.

What would be your approach?

答:
Well, I would appreciate not having to write everything from scratch but I think by doing this, the design would be much better.

This is a very wrong assumption. Testing has nothing to do with design. You need to understand the benefits of TDD in more details.

Ideally if you have a stable working product which do not require any change, test cases will not help you. Automated tests only help you with re-factoring or feature addition.

For an existing project, the best way is to analyse the change (re-factoring / feature / bug-fix) and then write test cases for only that code.

EDIT: I do no accept the fact that testing impacts. but even when it does, we have the problem of ends-means reversal. Design should be bases on problem domain, and not on testing . TDD is just a means to achieve the end, which in this case is solving the problem in hand.