问:
Why does Microsoft have such a bad reputation with the people involved in open source?
Are there any particular incidents which are responsible for the low reputation Microsoft (and Bill Gates) has in the eyes of the open source community? Microsoft is clearly not the only proprietary company. Companies like Apple have done a lot worse when it comes to restrictions on software. Why does Microsoft get most of the hatred from the open source community? </p>

答:
One more reason:

(I think it's not mentioned in the many existing answers yet - correct me if it is and I over-read it)

Microsoft has a history of picking existing and successful open source projects, creating a closed-source clone of it, and integrating it into Visual Studio.

Some examples:

Build tool: NAnt --> MSBuild

Unit testing tool: NUnit --> MSTest

OR Mapper: NHibernate --> Entity Framework

(yes, EF is open source now, but it wasn't when they first released it)

Mostly the Microsoft-made alternatives were seen as inferior by the community - at least by the community of the tool they cloned, and sometimes even by the whole .NET community.

And some generated a lot of heat - think about the Entity Framework Vote of No Confidence.

In the meantime, they partly changed their minds and did things like officially shipping jQuery with Visual Studio. Today we are used to this, but in 2008 that was a radical change.

But after that, they still created tools that did the same as already existing OSS projects, for example:

ServiceStack --> ASP.NET Web API

OpenWrap --> NuGet

...which probably causes a lot of people involved with open source to still hate Microsoft.


问:
Puzzle solving: Minimum number of steps to achieve a goal
I have been doing some programming contest problems, and I have noticed that many of them involve something along the lines of "get the minimum number of steps necessary to achieve a certain goal".

Examples:

Given the position of a knight and certain pawns in a chessboard, what is the minimum number of jumps the knight has to do to kill all the pawns?

Given a parking lot with disordered cars labeled alphabetically, a "move" is the process of taking a car and inserting it elsewhere. What is the minimum number of moves to get this parking lot ordered?

So, many puzzles seem to share this structure: given a scenario, some rules, and a set of "operations", determine the least amount of operations to achieve a specific goal.

There's a twist in some of these puzzles though - sometimes, the puzzles will also ask if it is impossible to achieve.

I have discovered that I am particularly terrible with this kind of puzzles. In fact, I don't think I have ever solved them in an elegant way ever.

I'm not sure how to "test all cases", "pick the shortest one" or "determine it is impossible". Can you advice me here?

For the sake of the question, we can base ourselves on the chess puzzle:

Example Problem

We got a chessboard. Each square is labeled with a number (which represents the position), from 1 to 64.

(Possible) Input

```<code>2 8 31 13
</code>```

This means "two pawns, on positions 8 and 31. The knight is on position 13."

Output

```<code>2
</code>```

Two steps. From position 13, the knight can jump to 8, and from 8, it can jump to 31.

The Question

How can I approach this kind of problem? I solved the chess one by generating a list of all possible steps and then I picked the shortest one. But that was very slow.

答:
There are more than a few different ideas one could employ on these kinds of problems:

Breadth-first search would be one technique to find the minimum moves for a problem that basically enumerates all possibilities.  While this is brute force there can be some applications of this technique that can work quite well.  The alternative to this is a depth-first search.

Dynamic programming would be another technique that may be used to generate answers assuming certain characteristics about the problem.  This can be used if one can break down a problem into smaller pieces and then build up which way to go.

Greedy algorithms would be another heuristic that can be useful with these kinds of problems as "making change" would be a classic that is solved with this method.

Divide and conquer would be another strategy that can be employed to solve some types of computing problems.  Mergesort would be an example of using this technique.

These are a few of the common methods that would be taught as part of an, "Introduction to Algorithm Design and Analysis" course that covers how to use these techniques.

ContentLicense: CC BY-SA 3.0


问:
Jenkins Paramerized Trigger + Copy Artifact
I'm working on setting up Jenkins to handle our release builds.  A release build consists of a Windows installer that includes some binaries that must be built on Linux.

Here's what I have so far:

The Windows portion and Linux portion are set up as separate Jenkins projects.

The Windows project is parameterized, taking the Subversion tag to build and release.

As part of its build, the Windows project triggers a build of that same Subversion tag for the Linux project (using the Parameterized Trigger plugin) then copies the artifacts from the Linux project (using the Copy Artifact plugin) to the Windows project's workspace so that they can be included in the Windows installer.

Where I'm stuck:  Right now, Copy Artifact is set up to copy the last successful build.  It seems more robust to configure Copy Artifact to copy from the exact build that Parameterized Trigger triggered, but I'm having trouble figuring out how to make that work.  There's an option for a "build selector" parameter that I think is intended to help with this, but I can't figure out how it's supposed to be set up (and blindly experimenting with different possibilities is somewhat painful when the build takes an hour or two to find success or failure).

How should I set this up?  How does build selector work?

答:
After you've completed a triggered build you'll have a new env variable set to the build number of that triggered build called TRIGGERED_BUILD_NUMBER_<job name>.  You can use that to specifically copy back the artifacts:

Windows build (called "WindowsBuild"), calls the Linux build (called
"LinuxBuild") using the Parameterized Trigger plugin.

You've got this part, just make sure to check Block until the triggered
projects finish their builds and fail the build of course if the Linux build fails.

Next in your Copy Artifacts from another project step:

Project name: LinuxBuild

Which build: Specific build

Build number: $TRIGGERED_BUILD_NUMBER_LinuxBuild
(All Project names have characters not a-zA-Z or 0-9 replaced by _ ; multiple characters are condensed into a single _).


问:
How do distributed version-control systems deal with fragmentation?
Here is the scenario:

X is the author of a software. X releases v1.0 on an open source license on Github and moves on. People interested in the software fork and improve the software. Now there are 15 different flavours of the software. Few also try to send a pull request back, however since X no longer works on the software, the pull request is just sitting idle on his project page.

As a new user wanting to use the most active and stable release of the software, how does he learn which out of the 15 he should clone and use? He certainly would like to use the more active branch, since it may have more bug fixes and features upgrades.

I see that the model works for bigger open-source projects, because the author of the software is usually well-known in the community. As a result, the user base inadvertently knows which branch to clone from. However, how does one solve a problem for a software, where the author, maintainer and several contributors all are practically unknown in the open-source community?

答:
As noted, this remains a problem.

I consider the following to determine viability:

Recent activity on the project.

Amount of activity on project.

If there is an identifiable owner of project.

Who else/what other projects is using the project.

Release history of project.

Determining suitability of a fork/application is non-trivial, no matter what type of software. Generally I'd look at:

Of other people using it to solve the same/similar problems you have.

Or, you can ask on stackexchange/stackoverflow.  :)


问:
Approach to simplifying an algorithm
For completely random reasons*, I wrote some code that calculates and displays the following expression:

P=1*(2+2)(3+3+3)(4+4+4+4)..(n+n...…

Which is equivalent to (n!)^2

The version I wrote (listed below the line) isn't terribly efficient; especially not in how it calculates the inner product.

How should I go about simplifying the algorithm so it will operate faster and be more easily understood?

And yes, I know I should use something other than int for the variables.  That aspect of my code isn't as interesting as re-working the algorithmic approach.

* In the spirit of full disclosure this off-topic question sparked my working on the code

int sequence(int n)
{
  int i, accum, prod, j;

  accum = 1;
  for (i = 2 .. n)
  {
    prod = i;
    for (j = 1 .. i-1)
    {
      prod += i;
    }
    accum *= prod;
  }
  return accum;
}
```

答:
How it goes for me usually is to first write code that literally performs the calculation or carries out some operations in the obvious non-clever way.  Then I look for patterns where I can substitute "better" code.

Some red flags or "code smells" I see in the example code:

There's one 'for' loop inside another.  If we're looping over i and j, maybe we could consider the sum i+j and difference i-j, with appropriate limits.  Very handy in quantum mechanics.  Probably nonsense for the typical business app.  There may be other ways to index things. Just a simple swap of inner/outer loops might lead to insight although probably not in itself improve speed.

Again, with nested loops. maybe there's a clever way to look at the two-dimensionality as a one dimensional problem.  Precalculate something, perhaps.  In the course of trying to improve the code, I may have an insight that lets me change the math or algorithm at an abstract level.

Look for obvious or almost-obvious math simplifications.  (4+4+4+4) of course is 4*4=4^2, and so for the general term I'd use n^2.  Right there, we lose a loop.   After that, recognizing the formula as computing 1*2*3*4*... is just n!, I will choose to use a lookup table.  If we weren't adding or multiplying but using trickier things like Legendre polynomials, root-sum-square, or using noisy experimental data instead of nice neat integers, then more sophisticated math is needed.  But then I work in physics and graphics not business, so most programmers in general may not need to get so deep into such things.

Plucking out things that are done over and over.  In your example we want to do "for n times: add n to a running total" and that could be put into a black box function or object or something.   Suppose your "4+4+4+4" and the like weren't just numbers and simple addition but something fancier such as images or audio tracks, and digital filters, FFTs, and modulators.  Shovel it into a black box.  It may not reduce the big-O complexity right away, but the contents of that black box could always be studied and optimized later. Hopefully we'd reduce its big-O growth but if not, we're likely to find some optimization to reduce the coefficient.  (E.g. it still helps to change an algorithm's execution time from 8*n^3 to 4*n^3.)

Sometimes, while doing the optimization work and waiting for compiles, I may websurf for other attempts to solve the problem, and find a whole different formula or method of solution, something so good that my algorithm can be ditched, never mind how it's implemented.

Title: Approach to simplifying an algorithm


问:
Is there a name for CSS code smell that can be seen in class names like "float" or "white"?
I noticed some code in our projects using CSS class names such as red, black or float.

I want to provide some information for people so they know to avoid it.

Is there a common name for that code smell so I can reference it?

答:
They are "non-semantic class names". That is, a class name should represent an idea, not how it should look or be laid out. That allows you to change the look and feel with a change in one place instead of everywhere that referenced class names red, black, float

There is one exception that exists for hacking purposes, for example if you need something that is implemented in different ways across browsers (the prefixed ones like gradients and others) and you don't want to repeat it every where. However, the better solution is to use SASS mixins.

.

OwnerDisplayName: Andrey Shchekin

OwnerDisplayName: Juan Mendes


问:
What are some database designs that support lineage tracing?

Environment

PostgreSQL 9.1

Java

Problem

I'll try to illustrate the problem here as simply as possible:

I'm trying to record the following relationship:

Node 1 => Node 2 => Node 3

Where Node 1 is the parent of Node 2, and Node 2 is the parent of Node 3.  In the database table, the initial design is tracking this data in a linked list fashion.  However, I am finding this extremely inefficient because each time I want to trace the lineage of say Node 1, I'd have to retrieve Node 2, then with Node 2, I'd retrieve Node 3.  Since I would be displaying the lineage of Node 1 to the user, I'd have to make 3 separate calls to the database to display this information.

I'd also like to backtrack, but for the sake of simplicity I left that part out.

Alternatives

Some alternatives I have considered, but I can't go to at this time are Neo4j and other solutions like it.  Unfortunately, at this time, I have to stay in Postgresql.

Question

Is there a design pattern such that I can retrieve all this information at once?  If there is, how would you implement with the example above?

UPDATE

With @MichaelT's comment, and finding Common Table Expressions, I've been lead to this link, which seems to provide more information on this:
https://stackoverflow.com/questions/53108/is-it-possible-to-make-a-recursive-sql-query

答:
While PostgreSQL's recursive query feature might be the way to go here, your relationship is also a special case of a directed acyclic graph (DAG). Take a look at https://stackoverflow.com/questions/4074794/simple-graph-search-algorithm-in-sql-postgresql and also consider switching from PostgreSQL to a graph database, like Neo4j.

Another possibility would be to add an additional ID to each record which associates parents, children, grandchildren, etc. into families. Parents and children could share a common family ID, which would be indexed, so retrieving all related records could be done in a single (fast) query. If you include backlinks, then it doesn't matter where you start from: you can work forward and backward through the result set to order the nodes. You could also bring the entire family into RAM for fast manipulation outside of PostgreSQL. Yes, there would be some additional overhead in maintaining consistent family IDs across CRUD operations, but you might realize a net win in performance.


问:
Unit Test code generation
We have a project that was written over a period of 2 years, but has a poorly designed architecture and not unit tests.

The software works well, but we're at the point where we want to refactor some core modules.

The budget is also limited so we can not hire a sufficient number of developers to write unit tests.

Would generating unit test code automatically to cover (as an example) integration scenarios via some too be a viable strategy? An assumpion is that considering the system works fine right now, and the its output can be converted into XML data for unit testing?

This approach gives us a possibility of quickly starting to refactor existing code and receieve immediate feedback if some core functionality is broken because of those changes.

答:
How are you going to generate matching input and output?  On one hand you have the output produced by the code being tested.  On the other hand you have -- what?  The output of a different implementation of the same algorithm?  That may make sense if there is a trivial but slow algorithm that can be used to test a more complex faster algorithm.  Or are you going to eyeball the expected output and just test against undesired changes?  It is very easy to accept incorrect output in that case.

In my experience generated tests are as valuable as the labor that goes into them.

Title: Unit Test code generation


问:
Invalidate cache over multiple applications
We have a suite of applications including a website, a client application and multiple windows services. All these applications work on the same dataset and use an in-memory cache. Of course, this setup fails when one of the applications does something that invalidates the cache. I'm looking for a solution that will allow me to invalidate the cache across the applications. We have some ideas, but I'm sure the collective minds of the internet can give us a better solution.

Some details:

this is a legacy application, which means we would like to keep the changes as non-invasive as possible

We're hesitant to introduce another moving piece to the solution. So using an external cache is out.

答:
Well, I think you are going to have to add a 'moving piece' here, if you want a new kind of motion :).

It seems to me that you are going to have to implement some kind of messaging between the applications to tell them to invalidate (part of) their cache.

It isn't clear in the question whether the whole cache becomes invalid for some reason, of if (much more common) a subset of the cache is becoming invalid.

In either case, there are a bunch of options on how to implement messaging.  You have to consider which is simpler, the messaging or an external cache.  I think most people would agree that the external cache is a better solution than attempting to maintain concurrency among various overlapping caches.

One last thought, you can also dodge this bullet if you can accept incorrect answers from the cache for certain periods of time.  For example, if each app reloaded 1/5th of its cache every minute, the worst-case scenario would be that a key changes immediately after it was reloaded.  Then for the next 5 minutes, that key is wrong, but, it will get reloaded after 5 minutes and assume the correct value.

OwnerDisplayName: Lodewijk


问:
Simple questions to test understanding of Dependency Inversion Principle
I am preparing a short (1-2 hour) presentation about DIP to several (~5) junior developers (1-3 yr xp) in the office. At the end of the presentation I want to know whether they understood what I was presenting, what are some possible questions that I ask in order to figure out their understanding? Maybe something that can be answered and explained by them in 3 minutes or less?</p>

答:
I often try to transpose the principles of OOD/OOP into real-life situations, as OOP arose largely as a result of the need to infuse real-life models into programming.  I don't think DI is missing from our everyday lives. Take the humble charger for example, pick anyone (except the iPhone charger). A large majority of manufacturers default to the micro-usb form factor for charging points. The advantages

To the user, you can essentially use any charger with any mobile phone. Contrast this with the iPhone and the latest charging port debacle and the DI pretty much justifies itself

To the manufacturer, a single production line can cater for all the charging unit needs of their entire product line.

If your students can adequately transpose the DI principle into real-life scenarios, IMO, it's a good reflection of their understanding of the principle


问:
What was the first programming language written for computers?
Looking at so many programming languages we have today, each one being unique in it's own way, I've tried to figure out what the first programming language written for computers is.

Looking at the release date for the popular ones I got somewhat close but I didn't look at less obvious ones, programming languages which are either dead or very little use nowadays. Fortran is the closest thing I got but I don't know if it's real.

In a nutshell: What was the first programming language written for computers? Are there any languages that derived from that language?

答: If you are willing to go back to the paper and punch cards (since the first programming languages predate the modern computer) the Jacquard loom, invented in 1801, used holes in punched cards to represent sewing loom arm movements. This could be considered the "first" code.</p>


问:
What are the consequences of immutable classes with references to mutable classes?
I've recently begun adopting the best practice of designing my classes to be immutable per Effective Java [Bloch2008].  I have a series of interrelated questions about degrees of mutability and their consequences.

I have run into situations where a (Java) class I implemented is only "internally immutable" because it is immutable except that it uses (immutable) references to other mutable classes.  To clarify, if the object were constructed with its references set to immutable classes, the class would be immutable.

Do any of the benefits (see below) of immutable classes hold true even by only "internally immutable" classes?

Is there an accepted term for the
aforementioned "internal mutability"?
Wikipedia's immutable object
page uses the unsourced term
"deep immutability" to describe an
object whose references are also
immutable.

Is the distinction between mutability and
side-effect-ness/state important?

The "Java Practices" site lists the following benefits of immutable classes:

are simple to construct, test, and
use

are automatically thread-safe and
have no synchronization issues

do not need a copy constructor

do not need an implementation of
clone

allow hashCode to use lazy
initialization, and to cache its
return value

do not need to be copied defensively
when used as a field

make good Map keys and Set elements
(these objects must not change state
while in the collection)

have their class invariant
established once upon construction,
and it never needs to be checked
again

always have "failure atomicity" (a
term used by Joshua Bloch) : if an
immutable object throws an exception,
it's never left in an undesirable or
indeterminate state

答: Immutability is useful when designing concurrent applications because of the object state guarantees it provides. It's also quite useful for Sets and as Map keys... As far as i am concerned there's no choice between immutability and mutability. As an example, in a multithreaded Bank application, an Account object cannot be made immutable because its a dynamic entity which changes overtime and its unique to one holder. However a Discount or APR can be designed as an Immutable object because they do not vary beyond definition. In short your problem domain will decide how you model your objects. Too many times Java programmers write code for "Gang Of Four" as opposed to coding to customer's requirement.</p>


问:
Why do we need "callback functions"?
I am reading the book programming in Lua. It said that

Closures provide a valuable tool in many contexts. As we have seen, they are
  useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example;
  this mechanism allows Lua programs to incorporate sophisticated programming
  techniques from the functional world. Closures are useful for callback functions,
  too. A typical example here occurs when you create buttons in a conventional
  GUI toolkit. Each button has a callback function to be called when the user
  presses the button; you want different buttons to do slightly different things
  when pressed. For instance, a digital calculator needs ten similar buttons, one
  for each digit. Y ou can create each of them with a function like this:

```<code>function digitButton (digit)
  return Button{label = tostring(digit),
                action = function ()
                  add_to_display(digit)
                  end}
end
</code>```

It seems that if I call the digitButton, it will return the action (this will create a closure), so, I can access the digit passed to digitButton.

My question is that:

```<code>Why we need call back functions? what situations can I apply this to?
</code>```

The author said:

In this example, we assume that Button is a toolkit function that creates new
  buttons; label is the button label; and action is the callback closure to be
  called when the button is pressed. The callback can be called a long time after
  digitButton did its task and after the local variable digit went out of scope, but
  it can still access this variable.

according to the author, I think a similar example is like this:

```<code>function Button(t)
  -- maybe you should set the button here
  return t.action -- so that you can call this later
end

function add_to_display(digit)
  print ("Display the button label: " .. tostring(digit))
end

function digitButton(digit)
  return Button{label = tostring(digit),
                action = function ()
                           add_to_display(digit)
                           end}
end

click_action = digitButton(10)
click_action()
</code>```

thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.

答:
Firstoff, the term callback refers to a closure that is being used for something.

For example, suppose you create a closure function and just store it in a variable. It isn't a callback, because it isn't being used for anything.

But, suppose you create a closure and store it somewhere that it will get called when something happens. It is now termed a callback.

Usually, callbacks are created by different parts of the program than the parts that call them. So it's easy to imagine that some parts of the program are "calling back" the other parts.

Simply put, callbacks allow one part of the program to tell another part to do something (anything) when something happens.

As for variables being kept alive due to being used in a closure, that's a completely different feature called upvalues (a.k.a. "extending the lifetime of local variables" among those who don't speak Lua). And it's quite useful as well.

Title: Why do we need "callback functions"?


问:
How does one make a cluster capable program?
In cluster computing, there seems to be two options: task redirection and task splitting. Task redirection seems easy enough, you just have the master dispatch the small calls to other nodes in the cluster for processing (eg webserver clusters (I think)). Task splitting however seems wildly more complex. Since I don't think you can have two threads of the same program run on different machines, meaning you have to split up the work.

How though does one split up the work? I can see some stuff like rendering or video encoding just because you can tell each node to work on a different part of the video, but when you want to do things like calculate the 5 trillionth digit of pie, how would you split that up? Or even in science where you need to simulate weather or other resource intensive tasks?

In short, how do you split up tasks that aren't really designed for splitting up?

答: Not every task is suitable for parallel processing. Factoring is, but long division isn't. We use the term Parallel algorithm to describe tasks which are designed to be executed in parallel (potentially on multiple computers, or using multiple cores of a single computer).</p>

ContentLicense: CC BY-SA 2.5


问:
Separation of concerns: Whose concern is this?
My senior reviewer colleague wants me to do the following.

We have (on iOS, iPhone) a hierarchy of views in one of our screens. There is a simple rectangle that represents a Business card of a person (visually matches business cards style).

As this card is reused many times in many screens, I have written a custom class called PFXBusinessCard that has four labels, each label representing person's data like Name, Phone number, account and email. These four labels are exposed as properties of that custom class.

In my controller, I am passing the data for a particular label in a following manner.
I get the person, read the particular value for a property and set this property in a controller. That is, I am setting the name, phone number etc..

But my colleague says I should instead handle this inside the PFXBusinessCard class.
I should create a populateWithPersonsData method in the class, and I would just pass a person to the card in my controller. The card would then populate its labels itself.

Is this approach ok? Why would the card should know about the person? The UI object should not know anything about the data. Should it?

答:
This is an issue that can be debated forever and in the end, both sides might be right.

There are two schools of thought in the application of the MVC pattern, which is what your question boils down to. I would name them the schools of the dumb View and the smart View.

In the dumb View, the View should concern itself only with UI matters and should not contain any logic (with the possible exception of iterating over a collection of values it needs to show). The controller is responsible for handing the data in bite-sized chunks to the View.

In the smart View, the View is allowed to have a limited amount of logic in it. In particular, the logic to convert objects from the Model into displayable values.

In my opinion, the smart View most closely resembles the formulation of the MVC pattern and should be preferred. It seems to me that the dumb View came about because for some it was too tempting to put business logic in the View (which does not belong there) and because it seemed that the Controller was losing its function.


问:
In a module-core program, how should modules interact with each other?
Short background: I'm using MEF/C# for developing a program that has one core (singleton) and multiple MEF parts (I call them modules, each module is a separate assembly with one class that contains the MEF export). The core imports all parts that are needed/available and initializes them (makes them read their configuration files, that stuff happens in the constructors, business as usual)

Now, my problem is that I need modules to interact with each other (say, module A, a graphical user interface, needs to get some data from a database, it'd need to somehow call a function on the database module (module B).)

How'd I do that? Sure, I could just make those parts/modules public in my core, add a reference to the core in my module and be done with it, but somehow, that'd feel ugly/bad. (mainly because I've security concerns over such an implementation, everyone could just call that function, unless I use something like this, but still it doesn't feel right).

Another approach would be to put all of those functions into the core, where they just call the corresponding function of the module. That feels bad, too because I'd have to add a lot of stuff to my core and in some cases that'd be something that a potential customer won't ever use because he doesn't need/have the specific module.

Does anyone know a better method of doing this? Maybe my train of thought went completely wrong somewhere?

答:
module A, a graphical user interface, needs to get some data from a database

This is indicative of an incorrect module design.

The point of dividing the code into modules is compartmentalization of functionality.  This means that each module should have a specific area of functionality, and do that only.

A GUI module should only handle the user interface.

A database module should only interact with the database.

Passing information from one to the other should happen at a higher level.  This might be your core module. Or, depending on what you are trying to do, it might make sense to add another layer.

Example:

If the user clicks on a button "Get my Data", an event handler in the GUI module calls a core method requesting data.  This core method then calls the database module to get the data.


问:
Is Ruby on Rails supposed to have a steep learning curve or is it just me?
I'm a self-taught programmer. I've been learning RoR since October with varying intensity (sometimes all day, sometimes nothing for several weeks). Before that I knew only Java, but knew it pretty well. I've heard so much hype about RoR and how it's supposed to make you happy, productive, etc. So far it's only made me frustrated.  I learned it out of the Agile book, and I suspect part of the difficulty might have to do with my not knowing JavaScript and CSS, and having only a shaky grasp of databases and HTML. But apparently it took me much longer to complete the project in the Agile book than other people, and I still don't remember much of it. There are some things about Rails that I just can't seem to get, e.g. when to use symbols and when NOT to, or how dynamic methods are called.

Recently I was given a small Rails assignment where I'm asked to make a small change to the interface. It's taken me around 25 hours and although I've made some progress in understanding the code, I still have no idea how to proceed. I can't even ask Stack Overflow because there is so much code I'll have to provide to give context.

So my question is in the title: is RoR supposed to take a long time to learn or am I just slow? Can it be that I've been learning from the wrong book? My learning style is such that I either understand nothing or understand everything, if that makes sense.

答:
Anita, I have had nearly the same experience as you. but think I now understand why it is so difficult to learn:

RoR is not one language, it is a wide collection of technologies, languages and techniques.

It is not like Java, C++ or other languages which have a logical structure

There is no one way to learn and no single book that can teach you (more on this later)

In my opinion, the community appears to have a somewhat "opinionated" attitude which is not as forgiving as other communities when learning. People regularly disagree on how things "should" be done. This comes from the top, from the guy who invented RoR

Testing is strongly encouraged to be a core part of development in most RoR lessons, and the testing languages are DSL's that can also add to the already high learning load.

There is not proper documentation for the language, only an API, some guides and whatever books you can find.

Some core methods and techniques are "automagical" and it is not clear how they work. For example, the has_secure_password methods.

I have been learning it for over a year now and here are some things that I think make it easier to learn, that I have come to from experience:

Attack it from several angles. When you have several books, tutorials and blogs to work from, this can "open" a way in for you to learn. A single book or blog on it's own can leave you "stuck".

Consider learning some HTML/CSS & Ruby. Not it all, just enough to get by, before you go too far in to RoR.

Take a course on RSpec (or similar testing methodology). The Codeschool one on RSpec is particularly good and this will stop you getting stuck in a RoR lesson because you cannot follow the testing.

Get about 3 books. Obie Fernandez "The Rails 3 Way" one is a must, used for reference when there is something you just don't get (not for cover to cover reading). The Agile one you mentioned just confused me. "Learing Rails 3" comes at things from a different direction and can help break down some issues you can't get from other tutorials.

Do a screencast or online learning course. Michael Hartl's tutorial is good, but very steep learning. I found that the books above, plus Codeschool course on RSpec, helped me get through it - but I still had to reach out to the author on a couple of small points.

Ask, ask, ask! There is a Ruby Forum, Rails Forum, IRC rooms and StackExchange etc - use them all, frequently!

Please don't give up - you are intelligent, but seem to have a learning style similar to me, and Rails is just very difficult to learn and not particularly well taught (completely) anywhere.


问:
Can I demand code quality on a project I've gotten
I have been given a Drupal project from an external web agency and have been trying to becomer wiser on both Drupal and their approach of making a site. With time I've learnt a bit morer about Drupal, even though I've come to notice it really isn't my cup of tea. Recently, I tried to "simply" replace the HTML generation of a part of the site, which seemed to be generated through a custom module (their addons for the site). I changed that code and realised that the effect simply didn't alter anything, or at least I thought.

Basicly now I've without exaggerating replaced the same piece of code with very small differences 26 times, and it's still not changing everywhere. So what I'm dealing with is a set of code that have literally never or barely heard of global class nor function and is simply copy & paste'd all over the site.

I'm curious on what I'm supposed to do with this. There's one file alone that has over 3000 lines of basicly the exact same code 16 times over. If you order a web agency to develop at site, can you expect it to be common sence that the code should be at least a little maintainable and simply not a big piece of code, more annoying to edit than far more necessary, or does it specifically have to be requested and I should had instead had to validate the code before paying for the handover of the site?

This is the first time I have ever came across such a poorly written piece of code in my career and it feels as if we bought a good looking suit that we saw from the outside of the store, and all we got was a poster of that suit for the same price.

The question

What would be the appropriate thing to do in my case? Should I suck it up and convince my employer that the code is poorly written in hope that my given deadline for completing the project gets extended, or can I demand the web agency to do some action?

EDIT:

Thanks for all your answers! They help me get some more perspective on this. I will discuss this internally a bit more, and try to mark out the best answer, even though most of yours covers the same but also different fields of the question.

答:
I've had to deal with something similar when we outsourced some front-end coding (HTML/CSS only) to a "web agency". What came back looked pixel perfect like the mockups, but was copy-and-pasted all over the place. The agency explicitly knew that they were working on non final front-end code, which would be brought to life with some backend code and some additional Javascript later on. They knew the code would need to be extended and changed. Yet they still delivered a copy-and-paste result.

The bottom line is, you can go back to the agency and ask for/request changes. The agency is responsible for delivering what has been specified in the contract. But that's the clincher: if certain code qualities have not been specified upfront, they have no real obligation.*

First of all, it's very difficult to quantify "code quality". You'll need to come up with some metric for this before you can hold anybody to this standard. Maybe "time required to implement a new feature x needs to be below y"; but good luck quantifying or proving that. And if it wasn't already in the contract, it doesn't really help you now.

Secondly and more importantly though: if they delivered code in this quality to you it means they either have no idea what they're doing or, more likely, they are a lowest bid outsourcer with a number of code monkeys working for them which crank out code like an assembly line. They have no interest in quality and it would cost them too much to deliver high quality, custom code. Either way, you're going to be running up against one wall or the other trying to demand higher quality code. I'm not saying it's not worth trying, but it will probably be mostly unsuccessful.

If they're cooperative you may be able to micro-manage them into delivering a high(er) quality product, but whether this investment of time and nerves is worth it is questionable.

The only real way to get quality code out of a contractor of unknown quality or to cut your losses is to specify very regular feedback and QA cycles. Demand that during development you get regular insight into the code (direct access to the repository preferred, daily or weekly snapshots as a fallback) and assess it on an ongoing basis. Specify a payment structure that allows you to withhold payments if you see that the quality is not up to your standards; establish regular feedback cycles that allow you to specify areas which need improvement and require the vendor to implement that feedback lest you stop paying. In the beginning both parties need to feel each other out to some degree; you need to assess the vendor's quality and the vendor needs to get used to the client's demands. A contract which appropriately protects both parties against loss of time and money in case it doesn't work out is a necessity if you're working with new people. In the beginning this will incur some overhead on your part, but if it works out well and you've established some mutual trust you'll be able cut down on your part of the work and leave it up to the vendor.

It's kind of a red flag if a vendor does not agree to such a contract.


答:
While I absolutely agree about demanding code quality, it IS very difficult to quantify, and if you have nothing in your contract with the agency then I don't see how you can get them to rework a presumably working solution.

Maybe the only thing you can take from this for the future is trying to come up with some kind of code quality control on top of your user acceptance testing when the provider deliver the solution.

If the code is really that bad, it may mean you simply do not hire that company again. There may be some mileage in informing the company of your concerns over their code quality, and in a bid to try and keep you as a customer, they may try and go above and beyond their contract, but your mileage will vary with this approach.

Title: Can I demand code quality on a project I've gotten

Body:
I have been given a Drupal project from an external web agency and have been trying to becomer wiser on both Drupal and their approach of making a site. With time I've learnt a bit morer about Drupal, even though I've come to notice it really isn't my cup of tea. Recently, I tried to "simply" replace the HTML generation of a part of the site, which seemed to be generated through a custom module (their addons for the site). I changed that code and realised that the effect simply didn't alter anything, or at least I thought.

Basicly now I've without exaggerating replaced the same piece of code with very small differences 26 times, and it's still not changing everywhere. So what I'm dealing with is a set of code that have literally never or barely heard of global class nor function and is simply copy & paste'd all over the site.

I'm curious on what I'm supposed to do with this. There's one file alone that has over 3000 lines of basicly the exact same code 16 times over. If you order a web agency to develop at site, can you expect it to be common sence that the code should be at least a little maintainable and simply not a big piece of code, more annoying to edit than far more necessary, or does it specifically have to be requested and I should had instead had to validate the code before paying for the handover of the site?

This is the first time I have ever came across such a poorly written piece of code in my career and it feels as if we bought a good looking suit that we saw from the outside of the store, and all we got was a poster of that suit for the same price.

The question

What would be the appropriate thing to do in my case? Should I suck it up and convince my employer that the code is poorly written in hope that my given deadline for completing the project gets extended, or can I demand the web agency to do some action?

EDIT:

Thanks for all your answers! They help me get some more perspective on this. I will discuss this internally a bit more, and try to mark out the best answer, even though most of yours covers the same but also different fields of the question.


问:
HTML code in Java class
A conceptual question, I tried to google but couldn't find any definitive answers, so here it goes:

Is it a good practice to write Java methods to return HTML strings that will be returned to the display/presentation layer?

Example:

```<code>public string getTextField(){
    return "<input type=\"text\"/>";
}
</code>```

答:
It's generally considered to be a bad idea in terms of 'modern' web development. Using a Javascript based templating framework such as angular.js allows you to cleanly separate your client-side code/logic from your server-side code/logic.

Having the HTML in your Java code makes it hard to validate, difficult to develop with rapidly (you have to recompile), difficult to debug etc.

Title: HTML code in Java class


答:
For me this is a massive code smell, regardless of the server side language.

It obfuscates how the pages are constructed and makes it much more difficult to understand when you have different concerns merged together.

This can make extending, debugging, and fixing a system all much more complicated.

I would be suspicious of the credentials of a colleague suggesting this as a way forward.

I'd be especially suspicious of a company selling me a solution and code base ie. the solution being so complicated I have to keep them around to maintain/extend it.

Title: HTML code in Java class

Body:
A conceptual question, I tried to google but couldn't find any definitive answers, so here it goes:

Is it a good practice to write Java methods to return HTML strings that will be returned to the display/presentation layer?

Example:

```<code>public string getTextField(){
    return "<input type=\"text\"/>";
}
</code>```


答:
No practice is totally good or totally evil, always depends on context. But some practices are more evil than others.

For a quick .jsp where the Java code is embedded in the HTML template directly, Java methods returning bit of HTML is OK. But for anything bigger than quick hack it is evil, because it is difficult to maintain.

The problem is that in larger application you want somebody to focus on the web design and other team members to do the backend. And for the designer it is easy to understand a decent templating system, but they will have big problems hunting down the snippets of HTML generated in methods buried deep within the backend.

The other problem is that you want the templating system to ensure a sane template leads to sane result. I am not sure what would be it's Java equivalent, but e.g. Genshi (python) checks that valid XML goes in and ensures valid XML goes out by automatically escaping all strings it interpolates and only accepting bits of HTML/XML as XML objects that contain the tree representation and therefore are always well formed. Such template system goes a long way towards avoiding cross-site scripting and similar attack opportunities.

Title: HTML code in Java class


答:
If the agency did terrible work the first time, there's every reason to believe that they will do so in the future. You might be able to talk them into doing more work without further payment (but I wouldn't count on it) and you might be able to supervise them closely enough that they deliver what you actually want, but that's highly likely to take so much work on your part that you might as well do the work yourself and save the time that would be spent on fruitless meetings.

Check the contract: if it was not clear in that that they needed to produce code that could be maintained and supported by others (i.e., yourself) then you just need to learn to write better contracts next time. If it was clear, consider legal action. And blacklist the agency, at least internally. Life is too short to deal with people who try to avoid their obligations one way or another, especially as there are plenty of others who are willing to deliver a quality product/service.


答:
Let's talk about responsibilities.

The GUI

handle input from user

request data

receive requested data

prettify / display data

The DB access layer

query database

process queried data

return processed data

Additional responsibilities

examine data requests to verify they're not malicious.  AKA scrub request for security.

There are two basic options in your case for who (which area) will handle the additional responsibilities.

GUI handles scrubbing responsibilities.  This keeps your DB layer clean at the risk of muddying your GUI code.  In addition, it places trust within the GUI code that may not be appropriate.

DBA layer handles the scrubbing responsibilities.  This resolves the trust concerns but it potentially muddies up the DBA layer code.

As an alternative, consider creating an additional layer whose responsibility is to scrub incoming data requests.  To facilitate the security review, I would encourage creating a specific data request object that holds the key elements you might be querying about (user ID, order numbers, date ranges, status codes, etc...).

This level of abstraction buys you a couple of notable advantages.

GUI no longer worries about formatting things for easy consumption by the DBA layer.

Scrubbing layer has a clean purpose and the security / validation code is located within the same area.

DBA layer can be linked to scrubbing layer and trigger security checks on the data request prior to operating upon the request.

Future changes to both the GUI and the DBA layer are facilitated since you now have a contract in place.  Data flow looks like:  GUI <=> AR <=> DBA. Future changes only have to be validated in regards to their half of the  contract instead of the whole contract.

Fortunately, quite a few folk have already worked through this challenge before.  The MVVM pattern ref 1, ref 2, ref 3 is worth reading for the overview and ideas on abstraction even if you don't choose to utilize the whole pattern.  It may be heavier to implement than what you wish to do.  MEF meshes well with this pattern, AFAIK.  Pro tip: That last reference is the MS developer guide to prism and is a veritable treasure trove of information for the area you are working within.

Title: In a module-core program, how should modules interact with each other?

Body:
Short background: I'm using MEF/C# for developing a program that has one core (singleton) and multiple MEF parts (I call them modules, each module is a separate assembly with one class that contains the MEF export). The core imports all parts that are needed/available and initializes them (makes them read their configuration files, that stuff happens in the constructors, business as usual)

Now, my problem is that I need modules to interact with each other (say, module A, a graphical user interface, needs to get some data from a database, it'd need to somehow call a function on the database module (module B).)

How'd I do that? Sure, I could just make those parts/modules public in my core, add a reference to the core in my module and be done with it, but somehow, that'd feel ugly/bad. (mainly because I've security concerns over such an implementation, everyone could just call that function, unless I use something like this, but still it doesn't feel right).

Another approach would be to put all of those functions into the core, where they just call the corresponding function of the module. That feels bad, too because I'd have to add a lot of stuff to my core and in some cases that'd be something that a potential customer won't ever use because he doesn't need/have the specific module.

Does anyone know a better method of doing this? Maybe my train of thought went completely wrong somewhere?


答:
Why have a core?

I mean if everything is comprised of modules, what does the core do? Why don't your modules reference each other (via interfaces) and then use MEF to spin up concrete implementations?

Then if some component of the UI needs to access some data repository, it asks for it via Import while ignoring the rest of the module, as well as what implementation is provided. Components of your modules can then work with each other (and/or mocked variants). Just be careful to use slim interfaces and not go crazy with responsibilities and it should work well.


答:
First: don't let the agency get any more work out of your project. That would confirm their business model (ie: hourly tasks given to junior devs for crazy money).

I guess from experience that they created some custom modules which suck and did not follow any of Drupal best practices. They may even have changed some core functionnality (like some custom made user modules) making you enable to follow the Drupal doc to create modules.

You will have to remove and refactor all this or this project is doomed. Your employer should suck it up and consider it a learning experience: web agencies are for small promotionnal projects, not anything with bigger scope.


问:
Dynamically change of UI on value changes in list box
I have a list box with several elements, let it be web servers (tomcat, iis etc). For each list box value, UI must have different views. For example, if we choose IIS, user name and password fields appear. If we choose tomcat, some additional fields appear depending on user OS - IP and port for linux and path for windows.

My current approach is the following:
- I created two enums. The first one for different OS (windows, linux, mac os x. The second one for servers: iis, nginx, tomcat etc.
- I have a method that returns the OS enum value.
- When user makes a choice, I determine it and basing on this choice I check user's OS. And after it I determine what UI elements to hide/add.

Here's some sort of pseudo-code for what I have:

```<code>//OS enum
public enum OS {
    WINDOWS, LINUX, MAC_OS_X;
}

//Servers enum
public enum SERVERS {
    TOMCAT, IIS, NGINX;
}

//Server Listbox Handler
private void chooseServer() {
        //...get value from list box
        switch(server) {
            case TOMCAT:
                changeUI(getOS()); //getOS() returns OS enum value
                break;
            case IIS:
                //IIS is for windows only
                changeUI(OS.WINDOWS);
                break;
            case NGNIX:
                //Temporary support only linux
                changeUI(OS.LINUX);
                break;
        }
    }

//UI changes here
private void changeUI(OS os) {
        switch (os) {
            case WINDOWS:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(true);
                break;
            case LINUX:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(true);
                portField.setVisible(true);
                serverPathField.setVisible(false);
                break;
            case MAC_OS_X:
                userNameField.setEnabled(false);
                userPasswordField.setEnabled(false);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(false);
                break;
        }
    }
</code>```

I don't like the moment when other OS or new servers will be added. These switch operators will grow more and become more complicated, I don't speak about maintainability of this code. Are there any standard approaches (patterns) for such tasks that help to avoid switch/if...else grow and to make code more generic, expandable, readable and supportable?

I tried to implement Adapter pattern suggested by Neil and ran at some obscure moment. Here's some pseudo-code:

```<code>public abstract class EditorAdapter {
    protected boolean firstInit = true;
    public abstract void adapt(Panel panel);
}

//--------

public class IISWindowsEditorAdapter extends EditorAdapter {
    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            panel.add(userNameField);
            //add other elements
        }
    }
}

//--------

public class TomcatEditorAdapter extends EditorAdapter {
    private OS os = getOS();

    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            if(OS == OS.LINUX) {
                panel.add(userNameField);
                //add other elements
            } else if (OS == OS.WINDOWS) {
                //add elements
            } //... else if
        }
    }
}

//--------

public class Editor extends DialogEditor { //extends Dialog with protected Panel field (subPanel)
    public Editor() {
        initialize();
    }

    public void initialize() {
        //...
        main.add(createPanel()); //protected VerticalPanel main;
        //...
    }

    public void createPanel() {
        //listBox initialization
        commonPanel.add(listBox); //panel with common elements
        listBox.addClickHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                selectServer();
            });
        }
        //... add other common elements
    }

    private void selectServer() {
        //... get selection
        switch(server) {
            //Here something should be done in order to control different layouts.
            //At the moment, each choice adds more elements in addition to existing ones
            //As a variant, one can create class fields for each adapter and manipulate with them using lazy initialization
            case IIS:
                new WindowsEditorAdapter().adapt(subpanel);
                break;
            case TOMCAT:
                new TomcatEditorAdapter().adapt(subpanel);
                break;
        }
    }
}
</code>```

The problem is that I have several tables/panels in my Editor that at the end are added to main panel. In general, it looks like:

we open a dialog

choose web-server

some elements change inside the dialog according to our choice (and some choices are affected with OS user is using).

That's why first UI initialization with adapter doesn't work here. At least I didn't catch how to implement this adapter for logic above.

答:
If your configuration is composed of boolean values, I think what you could have is the following structure comprising a BitSet:

```<code>class OSConfiguration {
  private BitSet configurationFields;

  public OSConfiguration() {
    configurationFields = new BitSet();
  }

  // you can allow checking if a given bitset index is set or not
  public boolean isFieldEnabled(int index) { return configurationFields.get(index); }

  // ... or create proper getter/setters
  public boolean isUserNameFieldEnabled() { return configurationFields.get(3); }
  public void setUserNameFieldEnabled(boolean value) { configurationFields.set(3, value); }
  // all other fields could be done like that
}
</code>```

And the following TreeMap:

```<code>TreeMap map = new TreeMap<SERVERS, Map<OS, OSConfiguration>>();

// to check if an OS configuration is available for a given server:
boolean isAvailable = map.get(SERVERS.TOMCAT).containsKey(OS.WINDOWS);

// to get an entire configuration:
OSConfiguration configuration = map.get(SERVERS.TOMCAT).get(OS.WINDOWS);
// to check if a given configuration is enabled:
boolean isEnabled = map.get(SERVERS.TOMCAT).get(OS.WINDOWS).isUserNameFieldEnabled();
</code>```

Now, even if your OS configuration needs to have more than just boolean values, since you've hidden that in the OSConfiguration class, you can do whatever you want.

In any case, I suggest to keep it simple.

Body:
If your configuration is composed of boolean values, I think what you could have is the following structure comprising a BitSet:

class OSConfiguration {
  private BitSet configurationFields;

  public OSConfiguration() {
    configurationFields = new BitSet();
  }

  // you can allow checking if a given bitset index is set or not
  public boolean isFieldEnabled(int index) { return configurationFields.get(index); }

  // ... or create proper getter/setters
  public boolean isUserNameFieldEnabled() { return configurationFields.get(3); }
  public void setUserNameFieldEnabled(boolean value) { configurationFields.set(3, value); }
  // all other fields could be done like that
}

And the following TreeMap:

TreeMap map = new TreeMap<SERVERS, Map<OS, OSConfiguration>>();

// to check if an OS configuration is available for a given server:
boolean isAvailable = map.get(SERVERS.TOMCAT).containsKey(OS.WINDOWS);

// to get an entire configuration:
OSConfiguration configuration = map.get(SERVERS.TOMCAT).get(OS.WINDOWS);
// to check if a given configuration is enabled:
boolean isEnabled = map.get(SERVERS.TOMCAT).get(OS.WINDOWS).isUserNameFieldEnabled();

Now, even if your OS configuration needs to have more than just boolean values, since you've hidden that in the OSConfiguration class, you can do whatever you want.

In any case, I suggest to keep it simple.


答:
What if you create category

```<code>@interface PFXBusinessCard (PersonData)
- (void)populateWithPersonsData:(PersonData *)personData
@end
</code>```

so your View class is not aware of Model class, but all this logic is still encapsulated, and you keep it DRY. It's subject to discuss.

Title: Separation of concerns: Whose concern is this?

Body:
My senior reviewer colleague wants me to do the following.

We have (on iOS, iPhone) a hierarchy of views in one of our screens. There is a simple rectangle that represents a Business card of a person (visually matches business cards style).

As this card is reused many times in many screens, I have written a custom class called PFXBusinessCard that has four labels, each label representing person's data like Name, Phone number, account and email. These four labels are exposed as properties of that custom class.

In my controller, I am passing the data for a particular label in a following manner.
I get the person, read the particular value for a property and set this property in a controller. That is, I am setting the name, phone number etc..

But my colleague says I should instead handle this inside the PFXBusinessCard class.
I should create a populateWithPersonsData method in the class, and I would just pass a person to the card in my controller. The card would then populate its labels itself.

Is this approach ok? Why would the card should know about the person? The UI object should not know anything about the data. Should it?

Body:
What if you create category

@interface PFXBusinessCard (PersonData)
- (void)populateWithPersonsData:(PersonData *)personData
@end

so your View class is not aware of Model class, but all this logic is still encapsulated, and you keep it DRY. It's subject to discuss.


问:
Service to prove authorship with trusted timestamp
This question is related with copyrights. The copyright is granted by default to the author of some code, however this requires to prove that some person is the "first" author of some piece of code. Consider the following example:

Andy writes some code in 2010 and stores it in a not secure enough place.

Brian copies that code in 2011 and registers this code in some service to associate it with some timestamp, to prove he had it written in 2011.

Andy decides he should be able to prove he is the author of the yet not published code and gets proceeds as Brian in 2012.

Carol has to judge who is the original author of that code in 2013 and all the evidence is in favor of Brian.

I think such a service is important and if I'm not mistaken there are some services like that which provide this for a price. At the same time nowadays there are quite a few git based services like Github, Bitbucket, Assembla, etc. that provide a version control system and store all the different versions made available for some code through time. They are free and offer really nice features. In some of them it is possible to define a repository as private and then switch it as public when the code is ready to be released.

The problem with the git based services is that they trust and believe the client on the dates for the commits. This means that if Brian commits in 2011 some code and publishes (pushes) it then David could manipulate the date in his computer to pretend he committed that code in 2009, beating Brian and Andy (the real author of the code).

So basically I would like to know if there is some kind of service like these that:

handles timestamps in a trustworthy way

allows publishing the code

allows publishing the different versions and diffs

allows private repositories that can be made public if shit happens

is free

So far, the most reasonable approach I found is sending something through mail. Even though the MIME headers can be manipulated the SMTP servers in the route should not be reasonably trustworthy and they set the timestamp for the time the mail goes through them.

This is a whole mess when compared with bitbucket, for instance, you cannot read my e-mails (I truly hope). Bitbucket allows private repos, repos can be made public with all the previous versions and diffs, etc. The only problem: the timestamps an be manipulated and thus they are not trustworthy.

So the question is: do you know about any service like this?

PD: Emails should be as valid as regular mail or escrows, even though they may raise more eyebrows among lawyers. But even if a tarball in an email is something simple to produce and do, it's much more natural to simply use some CVS, which should be used anyway. They do even have the timestamps already and I guess that should work in centralized systems like subversion, where the timestamp is set by the server. So maybe services that allow subversion repositories (SourceForge, Assembla, Google Code, etc.) could be enough? Would they be enough? Do you know about other (possibly better) alternatives? Assembla seems to be the only one fulfilling all the requisites.

Thank you.

答: There are escrow services, you can put your code in escrow for a fee. I'm not a lawyer, but I guess that would be enough to prove copyright? The other option is the standard Post Office copyright, put your code on a usb stick, in a tamperproof envelope, and mail it to yourself. Then when question of copyright comes up, you have your code available to you.</p>


问:
Do setters and getters always break the Single-Responsibility Principle?
As we know, The SRP states that every class should have single responsibility and that responsibility must be entirely encapsulated by the class.

But setters and getters do serve another responsibility - they do abstract class property(data) access.

if Setters and getters do abstract class property access, then they do serve another responsibility.

So if I have something like this,

```<code>class Config
{

    private location;

    public function write(array $data)
    {
        ....
    }

    public function read($key)
    {
        ...
    }

    public function exists($key)
    {
        ...
    }

    public function delete($key)
    {
        ...
    }

    // Below comes property abstraction

    // Here I doubt - I CANNOT USE this class without them
    // but they seem to break the SRP at the same time!?

    public function setFileLocation($location)
    {
        $this->location = $location;
    }

    public function getFileLocation()
    {
        return $this->location;
    }

    public function setConfigArray(...)
    {
        ...
    }

    public function getConfigArray()
    {
        ...
    }
}
</code>```

I do break the SRP. The problem is that, that's the only way class may exists.

So the question is,

In my situation, it's almost impossible to avoid setFileLocation() and getFileLocation() methods with CRUD ones.

So if by combining CRUD methods with Data Access abstraction I do break the SRP,

Is there any way I can adhere the SRP
and keep the common concept of the Config class (CRUD operations) at the same time?

答: Your config class has the responsibility of tracking configuration, which is implements by holding private references to certain data, and providing access to them through mutator methods. This does not break the SRP, because the class itself still has a single responsibility; the mutators simply help it accomplish that responsibility by abstracting access to the data. The mutators don't have a separate responsibility from that of the class; they are a part of the greater responsibility of the class.


答:
There are two distinct levels at which you can apply the SRP.

The first level is the level of individual functions/methods. Each should do only one task (and judging by the method names, none of the methods of Config break the SRP).

The second level is the level of a class. Here the concept of a single responsibility becomes a bit more abstract, but a good indicator is if you can state the responsibilities of a class in one sentence without the (implied) use of the word and. If you can do that with the presence of the getters and setters, then the class does not break the SRP.

In general, getters and, to a lesser extent, setters are, however, an indication that the encapsulation of a class is broken.
In the case of the Config class, the setFileLocation method is good, as Config needs some way to get to know where the data is located, but the others seem suspect, because they expose information that users of Config should not have a need for.

Title: Do setters and getters always break the Single-Responsibility Principle?

Body:
As we know, The SRP states that every class should have single responsibility and that responsibility must be entirely encapsulated by the class.

But setters and getters do serve another responsibility - they do abstract class property(data) access.

if Setters and getters do abstract class property access, then they do serve another responsibility.

So if I have something like this,

```<code>class Config
{

    private location;

    public function write(array $data)
    {
        ....
    }

    public function read($key)
    {
        ...
    }

    public function exists($key)
    {
        ...
    }

    public function delete($key)
    {
        ...
    }

    // Below comes property abstraction

    // Here I doubt - I CANNOT USE this class without them
    // but they seem to break the SRP at the same time!?

    public function setFileLocation($location)
    {
        $this->location = $location;
    }

    public function getFileLocation()
    {
        return $this->location;
    }

    public function setConfigArray(...)
    {
        ...
    }

    public function getConfigArray()
    {
        ...
    }
}
</code>```

I do break the SRP. The problem is that, that's the only way class may exists.

So the question is,

In my situation, it's almost impossible to avoid setFileLocation() and getFileLocation() methods with CRUD ones.

So if by combining CRUD methods with Data Access abstraction I do break the SRP,

Is there any way I can adhere the SRP
and keep the common concept of the Config class (CRUD operations) at the same time?


答:
The Bitcoin cryptocurrency can provide this service as a side effect of the currency bookkeeping method (the blockchain; a P2P shared ledger that's cryptographically signed).

Take a hash of your code at a given point in time (use some sort of version-control software to ensure you can get back to that point), and use a utility like BitcoinTimestamp to embed that hash in the blockchain (which automatically gives it a timestamp).

The popular Bitcoin dice game SatoshiDice uses that method to publicly verify that it hasn't changed its secret numbers since the time the hash was calculated.

This service can keep that timestamp around as long as some P2P node continues to broadcast the blockchain files. If the cryptocurrency fails, the P2P network may dissolve and you'd lose the ability to verify your timestamp, but that's true of any escrow service, and this system at least doesn't have a single point of failure (being a P2P network).

Title: Service to prove authorship with trusted timestamp

Body:
This question is related with copyrights. The copyright is granted by default to the author of some code, however this requires to prove that some person is the "first" author of some piece of code. Consider the following example:

Andy writes some code in 2010 and stores it in a not secure enough place.

Brian copies that code in 2011 and registers this code in some service to associate it with some timestamp, to prove he had it written in 2011.

Andy decides he should be able to prove he is the author of the yet not published code and gets proceeds as Brian in 2012.

Carol has to judge who is the original author of that code in 2013 and all the evidence is in favor of Brian.

I think such a service is important and if I'm not mistaken there are some services like that which provide this for a price. At the same time nowadays there are quite a few git based services like Github, Bitbucket, Assembla, etc. that provide a version control system and store all the different versions made available for some code through time. They are free and offer really nice features. In some of them it is possible to define a repository as private and then switch it as public when the code is ready to be released.

The problem with the git based services is that they trust and believe the client on the dates for the commits. This means that if Brian commits in 2011 some code and publishes (pushes) it then David could manipulate the date in his computer to pretend he committed that code in 2009, beating Brian and Andy (the real author of the code).

So basically I would like to know if there is some kind of service like these that:

handles timestamps in a trustworthy way

allows publishing the code

allows publishing the different versions and diffs

allows private repositories that can be made public if shit happens

is free

So far, the most reasonable approach I found is sending something through mail. Even though the MIME headers can be manipulated the SMTP servers in the route should not be reasonably trustworthy and they set the timestamp for the time the mail goes through them.

This is a whole mess when compared with bitbucket, for instance, you cannot read my e-mails (I truly hope). Bitbucket allows private repos, repos can be made public with all the previous versions and diffs, etc. The only problem: the timestamps an be manipulated and thus they are not trustworthy.

So the question is: do you know about any service like this?

PD: Emails should be as valid as regular mail or escrows, even though they may raise more eyebrows among lawyers. But even if a tarball in an email is something simple to produce and do, it's much more natural to simply use some CVS, which should be used anyway. They do even have the timestamps already and I guess that should work in centralized systems like subversion, where the timestamp is set by the server. So maybe services that allow subversion repositories (SourceForge, Assembla, Google Code, etc.) could be enough? Would they be enough? Do you know about other (possibly better) alternatives? Assembla seems to be the only one fulfilling all the requisites.

Thank you.


答:
It doesn't really matter as long as the class you say is immutable cannot be observed to be mutable.  E.g., memoisation uses mutation but a memoised value can be treated as immutable for all intents.

If I can't tell that your object uses mutable variables internally then it doesn't compromise my program and I can compose it with other objects as usual.

Title: What are the consequences of immutable classes with references to mutable classes?

Body:
I've recently begun adopting the best practice of designing my classes to be immutable per Effective Java [Bloch2008].  I have a series of interrelated questions about degrees of mutability and their consequences.

I have run into situations where a (Java) class I implemented is only "internally immutable" because it is immutable except that it uses (immutable) references to other mutable classes.  To clarify, if the object were constructed with its references set to immutable classes, the class would be immutable.

Do any of the benefits (see below) of immutable classes hold true even by only "internally immutable" classes?

Is there an accepted term for the
aforementioned "internal mutability"?
Wikipedia's immutable object
page uses the unsourced term
"deep immutability" to describe an
object whose references are also
immutable.

Is the distinction between mutability and
side-effect-ness/state important?

The "Java Practices" site lists the following benefits of immutable classes:

are simple to construct, test, and
use

are automatically thread-safe and
have no synchronization issues

do not need a copy constructor

do not need an implementation of
clone

allow hashCode to use lazy
initialization, and to cache its
return value

do not need to be copied defensively
when used as a field

make good Map keys and Set elements
(these objects must not change state
while in the collection)

have their class invariant
established once upon construction,
and it never needs to be checked
again

always have "failure atomicity" (a
term used by Joshua Bloch) : if an
immutable object throws an exception,
it's never left in an undesirable or
indeterminate state


答:
Honestly, I think you're taking the concept of single responsibility a little too far. Getters and setters are incidental to the functioning of the class whether you do it by direct access to public members or use methods (or properties) to do it.

You're making the argument that getting and setting some member of the class is a separate responsibility and should therefore be moved elsewhere.  Let's say we do that, and now you have classes called Config and ConfigAccessor.  At this point, you now have an air gap between the two classes, because Config has no interface to access its location member.  That makes it impossible to write ConfigAccessor, and you're left with an immutable, write-once class that's of no use whatsoever.  If you add some sort of interface to allow ConfigAccessor to do its job, you'll find yourself with a recursive problem.

The SRP, like many other things in this field is a principle, not a hard-and-fast rule.  That means you should be applying judgement to your situation instead of trying to follow it unconditionally.  There's a line between being a purist and getting the job done, and when the former is preventing the latter, you're on the wrong side of it.

If I can critique your design a bit:  If your Config class is designed to be an interface between a configuration file stored on disk and your code, the last thing you want to do is change its location midstream.  If you're changing the location as a way of starting access to a different file, you should be destroying the old object and creating a new one.  You didn't make clear whether you intend to store the contents of the file in the object.  If you'd planned to use it as a way to inhale the contents of one configuration file and write it to another, consider using a method that clones the data into a new object that points at the new file.


答: The card should know the person if displaying the person data is one thing it will do. Your colleague is right IMHO, because there must be logic for displaying PersonData somewhere in the whole code base. If controller wouldn't do it, so it belongs to the consumer of caller to map every properties of PersonData to your controller, and this logic will be scattered in your codebase. Any OOP design should bring more quality to the overall codebase, not reducing it.


问:
Options for Opensource license?
I am choosing a license for my open source software and I've learned about GPL, EBMS and BSD. GPL seems to be most popular one.

The problems are:

Would anybody kindly name a few popular opensource licenses? Since I do not see any EBMS BSD license is popular.

Are there any chart or table that have list out the advantages/disadvantages of using anyone?

Why is the GPL always the license developers choose from, what are its benefits?

答:
To get started, you really need to decide what kind of permissions you want to give. If you want your project very open with a lax license, go with a BSD or MIT style license. The only difference between those two is that the BSD requires people who distribute your software to keep your name with it, the MIT doesn't. If you want copyleft (requiring modified versions to have the same license), go with the GPL (or the LGPL if you are okay with your software being bundled). These licenses are often called viral licenses because they require forks of your program to be under that same license. They are also the #1 and #3 most popular licenses if I recall correctly. If you want the same kind of protections as the GPL minus the copyleft, look at the Apache License, which is the #2 most popular license and is also used for it's sections regarding patents. Documentation should also be openly licensed, try the GFDL or a Creative Commons license for it.

I don't really know why the GPL is chosen so much. It's quite possible that the Free Software Foundation's pamphlets on copyleft convinced them that is what they needed to do. I take a much more lax approach and license my stuff using the Apache License or the BSD. You could also go in between and choose the LGPL, which provides the same protections as the GPL, but includes the ability for other people to bundle your software without dealing with copyleft. It's generally used for libraries, but other programs like LibreOffice have chosen to use it for it's ability to allow software to be bundled in packages with other software while retaining the copyleft requirement for forks.

I am not a lawyer, this is not legal advice. Blah blah blah, etc.

Title: Options for Opensource license?


问:
How should I implement my chosen software license?
I have always kind of wondered, but never took my time to actually ask these questions regarding licensing. Most of these questions are presumably pretty basic, but I have no idea what I'm dealing with here.

The thing that baffles me the most is how exactly you "implement" the license for your OSS. Is just saying in the post you're publishing the code on, "by the way, this is licensed under GPL" enough? Or should something more delicate take place, like registering the software somewhere? Also,

If I just say I use a particular license, is that enough?

Do I add a copy of the license to the distributed code?

Am I required to add a header on every file detailing the licensing information? Do I manage this with my version control system (e.g. Subversion)?

Is the above not enough?

What are the most commonly used software licenses?

Are there any gotchas/licenses that are better left alone?

答:
What I do, which appears to generally be the standard, is to create a file called COPYING in the root directory of your project containing the license code. You should also create a file called COPYRIGHT in the same folder as the other file and include something like this (written in Markdown since most distro sites like that):

```<code><name of your project> <version>
-----
<short description of the program>
***
Copyright <major release years, e.g. 2006-2010> <copyright owner>
<the boilerplate text typically at the bottom of most licenses>
</code>```

You could also call this file README and add any other info you want to pass along with your program. Finally, if you use a short license like the BSD or the MIT, don't add the COPYING file and simply use the full license instead of the boilerplate text in the README or COPYRIGHT file.

APPENDIX: The weird guy is the LGPL. You need to include both the GPL in the COPYING file and the LGPL in a file called COPYING.LESSER, since in the eyes of the law the LGPL is an extension onto the rights of the GPL.

Body:
What I do, which appears to generally be the standard, is to create a file called COPYING in the root directory of your project containing the license code. You should also create a file called COPYRIGHT in the same folder as the other file and include something like this (written in Markdown since most distro sites like that):

<name of your project> <version>
-----
<short description of the program>
***
Copyright <major release years, e.g. 2006-2010> <copyright owner>
<the boilerplate text typically at the bottom of most licenses>

You could also call this file README and add any other info you want to pass along with your program. Finally, if you use a short license like the BSD or the MIT, don't add the COPYING file and simply use the full license instead of the boilerplate text in the README or COPYRIGHT file.

APPENDIX: The weird guy is the LGPL. You need to include both the GPL in the COPYING file and the LGPL in a file called COPYING.LESSER, since in the eyes of the law the LGPL is an extension onto the rights of the GPL.


问:
Open Source, Copyright and Trivial Bugfixes
Say a developer has developed a library for their closed-sourced commercial application. Since they want to give back to the open source community, they publish this library under, say, the GPL, but continue to use it in their own application. Since they hold the copyright, that's fine.

Now, a user of the GPL version finds a bug, fixes it and submits a patch to the original developer. As I understand it, to use this bugfix in their closed-source application, the developer needs to have permission from the submitter. If the submitter refuses, the developer has to find another way to fix the bug in the closed-source version.

But what if the bugfix itself is really trivial? Like properly initializing a variable or checking for a null pointer? Something that any half-competent programmer can find and fix in a matter of minutes, given an error description? Is the patch for this still protected by copyright? Or can the original developer implement the identical fix in their closed-source application without consent of the submitter?

Note: This really is a hypothetical scenario, not one of those "my 'friend' has this problem" questions

答:
If the bugfix is really trivial, then it likely isn't copyrightable at all, especially if there really isn't any other way to write the code.  There are hundreds of millions of ways of writing a love poem or a video game, there really aren't more than one or two ways to write if (*p == NULL).  Copyright is on the expression of an idea, so if there isn't really any choice in how an idea is expressed, there can't be a copyright.

However, if the bugfix is still fairly trivial, there could be a few dozen ways of expressing it, so it could be copyrightable.  And it might not be easy to tell whether something that's fairly trivial is barely copyrightable or barely uncopyrightable.

It is also possible that it might be copyrightable, but that using it would be fair use.  Fair use is a bit complicated, since it depends on weighing several factors, and it might not be helpful, since whether fair use applies would be decided by a court -- ideally, you don't want there to be a court case at all, however strong your case might be.  One of the factors of fair use is the fraction of the work that was used (this is against you, since you took the whole thing), and another is the commercial potential of the work (this is for you, since the commercial value of a trivial bugfix by itself is zero), so guessing which way a court might rule is error-prone.

Probably the best way to deal with this is to hand an exact description of the bug and its exact location to a developer who hasn't seen the patch.  They can then independently fix the bug (which will take very little time, since this bug is trivial), and all of the potential copyright problems disappear, since if it is copyrightable, you own the copyright.  Your developer may end up with nearly exactly the same code as the patch because there is essentially only one way to write it, but in this case it isn't copyrightable.


问:
Nested languages code smell
Many projects combine languages, for example on the web with the ubiquitous SQL + server-side language + markup du jour + JavaScript + CSS mix (often in a single function). Bash and other shell code is mixed with Perl and Python on the server side, evaled and sometimes even passed through sed before execution. Many languages support runtime execution of arbitrary code strings, and in some it seems to be fairly common practice. In addition to advice about security and separation of concerns,

what other issues are there with this type of programming,

what can be done to minimize it, and

is it ever defensible (except in the "PHB on the shoulder" situation)?

Edit: To clarify, this is not about using more than one language for the job - That's a good thing for any but the simplest projects. The issue is mixing languages in the same file, such as magic strings for SQL, Bash & Perl eval, and the like.

答:
If you mix PHP (or other server side language) with JS, your JS won't be cacheable (if your PHP isn't).

Nested languages are like code generators, very hard to understand the generated code

My solution is to minimize the coupling between different languages by never generating code, using JSON as the data transfer between languages

PHP example (tightly coupled)

```<code>var arr = [];
<?php
foreach($value in $phpArray) {
    echo "arr.push('$value');\n";
}
?>
</code>```

PHP example (loosely coupled)

```<code>var arr = <?php echo json_encode($phpArray) ?>;
</code>```

Notice that with json_encode, you don't have to worry about escaping strings or any other values.

Title: Nested languages code smell

Body:
If you mix PHP (or other server side language) with JS, your JS won't be cacheable (if your PHP isn't).

Nested languages are like code generators, very hard to understand the generated code

My solution is to minimize the coupling between different languages by never generating code, using JSON as the data transfer between languages

PHP example (tightly coupled)

var arr = [];
<?php
foreach($value in $phpArray) {
    echo "arr.push('$value');\n";
}
?>

PHP example (loosely coupled)

var arr = <?php echo json_encode($phpArray) ?>;

Notice that with json_encode, you don't have to worry about escaping strings or any other values.


问:
What is detailed design? what are the advantage disadvantages using it?
Im really not getting  the idea:

What is Detailed Design.

Why use Detailed Design.

Advantages/Disadvantage of using Detailed Design.

Any alternative methods other than using Detailed Design.

Could some one please guide/explain me ?

答: A detailed design allows you to evaluate design options prior to actually implementing them. It can potentially save you a ton of needless work you would otherwise have spent on an implementation that was deeply flawed due to a high level design choice and had to be extensively rewritten.


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答: Yes, splitting long functions is normal.  This is a way of doing things that's encouraged by Robert C. Martin in his book Clean Code.  Particularly, you should be choosing very descriptive names for your functions, as a form of self-documenting code.</p>


答:
Testing code that does lots of things is difficult.

Debugging code that does lots of things is difficult.

The solution to both of these problems is to write code that doesn't do lots of things.  Write each function so that it does one thing and only one thing.  This makes them easy to test with a unit test (one doesn't need umpteen dozen unit tests).

A co-worker of mine has the phrase he uses when judging if a given method needs to be broken up into smaller ones:

If, when describing the activity of the code to another programmer you use the word 'and', the method needs to be split into at least one more part.

You wrote:

I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods.

This should be at least two methods.  It is ok to wrap them in one publicly facing method, but the workings should be two different methods.

Title: Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

Body:
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.


问:
Why does Haskell have built-in "if/then/else" instead of defining it as a simple library function?
Why does Haskell have a built-in if/then/else, which is dependent on the Bool type, instead of having a simple library function? Such as

```<code>if :: Bool -> a -> a -> a
if True  x _ = x
if False _ y = y
</code>```

答:
It doesn't matter much ... to me it looks like if/then/else is not used very often nowadays. I find myself writing pattern guards instad of if .. then .. else.

From a syntactic point of view, though, it is nice to have

```<code>if expr1 then expr2 else expr3
</code>```

So you can write

```<code>if foo a then bar b else baz c
</code>```

instead of

```<code>if (foo a) (bar b) (baz c)
</code>```

which looks a bit too LISPish to me.

For semantic analysis and code generation, it is nice to have this construct, which can easily be compiled to efficient machine code. Note that the code can skip the part that makes the thunk for the branch that is not reached, as opposed to a function call, where the (unevaluated) parameters must all be passed. But it also costs time (and memory, that must be reclaimed later) to create the thunk. To make good on this, one would have to inline the if function everywhere.

Body:
It doesn't matter much ... to me it looks like if/then/else is not used very often nowadays. I find myself writing pattern guards instad of if .. then .. else.

From a syntactic point of view, though, it is nice to have

if expr1 then expr2 else expr3

So you can write

if foo a then bar b else baz c

instead of

if (foo a) (bar b) (baz c)

which looks a bit too LISPish to me.

For semantic analysis and code generation, it is nice to have this construct, which can easily be compiled to efficient machine code. Note that the code can skip the part that makes the thunk for the branch that is not reached, as opposed to a function call, where the (unevaluated) parameters must all be passed. But it also costs time (and memory, that must be reclaimed later) to create the thunk. To make good on this, one would have to inline the if function everywhere.