答:
You don't have to store all the packages for the queries you have mentioned. For example - package type counter:

You need two arrays:

```<code>int[] packageCounters = new int[NumberOfTotalTypes];
int[,] counterDifferencePerMinute = new int[6, NumberOfTotalTypes];
</code>```

The first array keeps track of how many packages in different types. The second array keeps track of how many more packages been added in every minutes such that you know how many packages need to be removed at every minute interval. I hope you can tell that the second array is used as a round FIFO queue.

So for each package, the following operations are performed:

```<code>packageCounters[packageType] += 1;
counterDifferencePerMinute[current, packageType] += 1;
if (oneMinutePassed) {
  current = (current + 1) % 6;
  for (int i = 0; i < NumberOfTotalTypes; i++) {
    packageCounters[i] -= counterDifferencePerMinute[current, i];
    counterDifferencePerMinute[current, i] = 0;
}
</code>```

At any time, the package counters can be retrieved by the index instantly and we don't to store all the packages.

Body:
You don't have to store all the packages for the queries you have mentioned. For example - package type counter:

You need two arrays:

int[] packageCounters = new int[NumberOfTotalTypes];
int[,] counterDifferencePerMinute = new int[6, NumberOfTotalTypes];

The first array keeps track of how many packages in different types. The second array keeps track of how many more packages been added in every minutes such that you know how many packages need to be removed at every minute interval. I hope you can tell that the second array is used as a round FIFO queue.

So for each package, the following operations are performed:

packageCounters[packageType] += 1;
counterDifferencePerMinute[current, packageType] += 1;
if (oneMinutePassed) {
  current = (current + 1) % 6;
  for (int i = 0; i < NumberOfTotalTypes; i++) {
    packageCounters[i] -= counterDifferencePerMinute[current, i];
    counterDifferencePerMinute[current, i] = 0;
}

At any time, the package counters can be retrieved by the index instantly and we don't to store all the packages.


问:
SOLID vs. static methods
Here's a problem I frequently run into: Let there be a web shop project that has a Product class. I want to add a feature which allows users to post reviews to a product. So I have a Review class which references a product. Now I need a method that lists all reviews to a product. There's two possibilities:

(A)

```<code>public class Product {
  ...
  public Collection<Review> getReviews() {...}
}
</code>```

(B)

```<code>public class Review {
  ...
  static public Collection<Review> forProduct( Product product ) {...}
}
</code>```

From looking at the code, I'd choose (A): It's not static and it doesn't need a parameter. However, I sense that (A) violates the Single Responsibility Principle (SRP) and the Open-Closed Principle (OCP) whereas (B) doesn't:

(SRP) When I want to change the way reviews are collected for a product, I have to change the Product class. But there should be only one reason why to change the Product class. And that's certainly not the reviews. If I pack every feature that has something to do with products in Product, it'll soon be clattered.

(OCP) I have to change the Product class to extend it with this feature. I think this violates the 'Closed for change' part of the principle. Before I got the customer's request for implementing the reviews, I considered Product as finished, and "closed" it.

What is more important: following the SOLID principles, or having a simpler interface?

Or am I doing something wrong here altogether?

Result

Wow, thanks for all of your great answers! It's hard to pick one as official answer.

Let me summarize the main arguments from the answers:

pro (A): OCP is not a law and readability of the code matters as well.

pro (A): the entity relationship should be navigable. Both classes may know about this relationship.

pro (A)+(B): do both and delegate in (A) to (B) so Product is less likely to be changed again.

pro (C): put finder methods into third class (service) where it's not static.

contra (B): impedes mocking in tests.

A few additional things my colleges at work contributed:

pro (B): our ORM framework can automatically generate the code for (B).

pro (A): for technical reasons of our ORM framework, it will be necessary to change the "closed" entity in some cases, independently from where the finder goes to. So I won't always be able to stick to SOLID, anyway.

contra (C): to much fuss ;-)

Conclusion

I'm using both (A)+(B) with delegation for my current project. In a service-oriented environment, however, I'll go with (C).

答:
I wouldn't put the 'Get Reviews For Product' functionality in either the Product class nor the Review class...

You have a place where you retrieve your Products, right? Something with GetProductById(int productId) and maybe GetProductsByCategory(int categoryId) and so on.

Likewise, you should have a place to retrieve your Reviews, with a GetReviewbyId(int reviewId) and maybe a GetReviewsForProduct(int productId).

When I want to change the way reviews are collected for a product, I
  have to change the Product class.

If you separate your data access from your domain classes, you won't need to alter either domain class when you change the way the reviews are collected.

ContentLicense: CC BY-SA 3.0

Title: SOLID vs. static methods


问:
How do you manage feature requests and software changes?
I am a Software Engineer and over the past few years I have become the de-facto software project manager simply because there isn't one. So to keep our sanity in the R&D/Engineering department, customers have become accustomed to coming to me with their requests. I have no experience in this realm so it is my first time acting as a project manager for software projects. I have managed other things but not software.

So, how do you manage software projects and mark priorities? Requests come in at infrequent intervals so we very well could be working on something for someone else and then another person comes in with a "rush" job that needs working on. Is it easier to just say First Come, First Serve or is it the person with the most money?

答:
I like 's principles:

QI - Important and Urgent

QII - Important but Not Urgent

QIII - Not Important but Urgent

QIV - Not Important and Not Urgent

ContentLicense: CC BY-SA 2.5


问:
How do I dive deep into code that does not have a single entry point?
I work on enterprise Java projects that do not have a single entry point from where I can trace the flow of execution. Some of the projects have hundreds of classes, and when I'm asked to add a feature to a project, I often find myself at a loss as to where to start looking at code.

What's the best way to dive into such projects so that I can implement the feature quickly without wasting time.

答:
Does the project have a suite of well-maintained unit tests?  The unit tests are programmatic documentation for what the code does.

In addition, you need to learn enough about the architecture of the application to identify the places where you need to insert code for your new features, and more or less ignore the rest.  You don't need to know the whole code base to do this; if the projects are well-architected, the functionality is already sufficiently encapsulated and decoupled that you can focus on the relevant parts.  If you're lucky, the projects already follow a well-known architecture which will serve as a map for you to follow.

Code always has one or more entry points.  For MVC projects, the entry point is a controller method based on an URL; the method will almost certainly access a data repository, and return a view.  Start there.


答:
Start with the middle tier( business logic layer).

That is one of the places the control comes for any user actions or trigger events if it is a non UI based application. If you are in debug mode, You can trace it to the top and bottom ( most likely data access layer).

It will take sometime but this is the efficient way to jump into undocumented projects.

If the project uses any framework ( struts-config.xml , ejb config xmls , spring config xmls) will have a defined interfaces and you can start from there as well.

Title: How do I dive deep into code that does not have a single entry point?

Body:
I work on enterprise Java projects that do not have a single entry point from where I can trace the flow of execution. Some of the projects have hundreds of classes, and when I'm asked to add a feature to a project, I often find myself at a loss as to where to start looking at code.

What's the best way to dive into such projects so that I can implement the feature quickly without wasting time.


答:
I would start with a class hierarchy.  If you have one great, if not, find a tool that can reverse engineer your code and create one for you.  From that you can start to see how things may be related.  Once you can see how things may be related you can at least target areas instead of having a large "hodgepodge" of classes.  You can target an area you can see how they are associated with each other (is this class an association of this one, is this set of classes a design pattern, etc).  Attempt to add some order and structure around what you're looking at and then break down each section.

EDIT:

Here are some posts from stack overflow outlining the tools you could use in eclipse (or as standalone applications) to reverse engineer and generate a model:

https://stackoverflow.com/questions/51786/recommended-eclipse-plugins-to-generate-uml-from-java-code

https://stackoverflow.com/questions/43344/is-there-some-tool-to-visualize-java-class-hierarchies-and-relations

"How do you eat an elephant".
"One bite at a time".


问:
How is CoffeeScript influenced by Haskell?
I've been using CoffeeScript for a while now. On Wikipedia, it is said that CoffeeScript is influenced by Haskell. But after I check out the syntax of Haskell, I have found little resemblance from CoffeeScript.

Which aspect of CoffeeScript is influenced by Haskell?

答:
Coffeescript is a gateway drug for Haskell.  Let's take a look at the Quicksort algorithm, as presented in Chapter Five of Learn You A Haskell For Great Good:

```<code>quicksort [] = []
quicksort (x:xs) =
       let smallerOrEqual = [a | a <- xs, a <= x]
           larger = [a | a <- xs, a > x]
       in quicksort smallerOrEqual ++ [x] ++ quicksort larger
</code>```

And the equivalent in Coffeescript:

```<code>quicksort = (x) ->
    return [] if x.length == 0
    h = x.pop()
    smallerOrEqual = (a for a in x when a <= h)
    larger = (a for a in x when a > h)
    (quicksort smallerOrEqual).concat([h]).concat(quicksort larger)
</code>```

The only obvious difference between these two bits of code is that the pattern had to be turned into a guard condition.

These are not equivalent pieces of code.  The Haskell code will only do the list comprehensions lazily, i.e. when needed by the in line.  Pattern recognition is a big deal in Haskell.  Haskell will optimize this code with tail-recursion, whereas Coffeescript will just build a framestack as big as the number of recursions needed.  And the Haskell version cares about the contents of the list and demands they be all of the same type, since Haskell is so strongly typed.

But one could be fooled, by their clear syntactical resemblence, into believing they were equivalent.  And to some extent, a smart developer could use that resemblence to write Coffeescript that, if not lazy or strongly typed, was nonetheless better disciplined and more functional.  Haskell is an excellent language for learning that discipline, and those skills are directly translatable to Coffeescript's syntax.

[EDIT] Building on Linus's excellent addition below, we can even simulate Haskell laziness:

```<code>quicksort = ([x, xs...]) ->
    return [] unless x?
    smallerOrEqual = -> (a for a in xs when a <= x)
    larger = -> (a for a in xs when a > x)
    (quicksort smallerOrEqual()).concat(x).concat(quicksort larger())
</code>```

Now the two expressions only trigger when their results are needed, not just imperatively.  I doubt this actually wins you anything, but it does seem to be getting closer to some Haskellian purity.

OwnerDisplayName: lightblade

Body:
Coffeescript is a gateway drug for Haskell.  Let's take a look at the Quicksort algorithm, as presented in Chapter Five of Learn You A Haskell For Great Good:

quicksort [] = []
quicksort (x:xs) =
       let smallerOrEqual = [a | a <- xs, a <= x]
           larger = [a | a <- xs, a > x]
       in quicksort smallerOrEqual ++ [x] ++ quicksort larger

And the equivalent in Coffeescript:

quicksort = (x) ->
    return [] if x.length == 0
    h = x.pop()
    smallerOrEqual = (a for a in x when a <= h)
    larger = (a for a in x when a > h)
    (quicksort smallerOrEqual).concat([h]).concat(quicksort larger)

The only obvious difference between these two bits of code is that the pattern had to be turned into a guard condition.

These are not equivalent pieces of code.  The Haskell code will only do the list comprehensions lazily, i.e. when needed by the in line.  Pattern recognition is a big deal in Haskell.  Haskell will optimize this code with tail-recursion, whereas Coffeescript will just build a framestack as big as the number of recursions needed.  And the Haskell version cares about the contents of the list and demands they be all of the same type, since Haskell is so strongly typed.

But one could be fooled, by their clear syntactical resemblence, into believing they were equivalent.  And to some extent, a smart developer could use that resemblence to write Coffeescript that, if not lazy or strongly typed, was nonetheless better disciplined and more functional.  Haskell is an excellent language for learning that discipline, and those skills are directly translatable to Coffeescript's syntax.

[EDIT] Building on Linus's excellent addition below, we can even simulate Haskell laziness:

quicksort = ([x, xs...]) ->
    return [] unless x?
    smallerOrEqual = -> (a for a in xs when a <= x)
    larger = -> (a for a in xs when a > x)
    (quicksort smallerOrEqual()).concat(x).concat(quicksort larger())

Now the two expressions only trigger when their results are needed, not just imperatively.  I doubt this actually wins you anything, but it does seem to be getting closer to some Haskellian purity.


问:
Why such popularity with Python?
Other than being annoyed at whitespace as syntax, I'm not a hater, I just don't get the fascination with Python.

I appreciate the poetry of Perl, and have programmed beautiful web services in bash & korn, and shebang gnuplot.  I write documents in troff and don't mind REXX.  Didn't find tcl any more useful years ago, but what's the big stink about Python?  I see job listings and many candidates with this as a prize & trophy on their resumes.

I guess in reality, I'm trying to personally become sold on this, I just can't find a reason.

答:
Since 2004, I've used Python to develop:

GUIs

Scripting ray tracer scenes with Python to C++ bindings

Cross platform automated build systems

Test scripts

General purpose tools to solve your everyday issues

Web sites and web apps

Back in 2004, Python was the language of choice because Python scripts are portable across Windows, Linux and Mac with very little modifications.

Title: Why such popularity with Python?


问:
Is it possible (or desirable, if not) to make an database engine organize the order of sql statements to maintain the referential integrity?
Today at work I found the following situation:

We had two tables, A and B, with B having a foreign key linked to the primary key of A.

On our application, we got two main situations that created the problem :

One where we had to add add some records in A, followed by the creation of some records in B referring to the ones in A. This was just fine, since we created our BLL to handle first the changes in A and them B. The "problem" is, sometimes we will have to delete the records of B and them delete the referred record in A, wich raises an error, since we are trying to delete A before deleting B, what could break the referential integrity of these tables. Of course everything is inside a transaction, and we could deal with that in our BLL code, simply changing the order of wich changes cames first (in A or in B) based on the actions that have to be made, but my question is more conceptual than a "please help me solve my problem" one, since the "problem" is already solved (but of course, I'm accepting suggestions if they came up! =D).

Chatting in the office, we agreed that, inside a transaction, everything is being donne and if some problem occurs, what was done is rolled back.

My idea: Why can't the transaction evaluate everything and them order the statements and execute that in a way that don't break the referential integrity, since after the transaction everything will be done and the order might not matter at all? After thinking a little about it, even I am not sure if this thing would be nice or create some king of living hell, since I can think of some situations where the order of the statements would matter, so I'm posting it here so we can discuss about it.

I hope that my text is not confusing. And just to mention, I'm using Microsoft SQL Server. Dunno if this is possible in other databases.

答:
It simply doesn't work that way... When a transaction starts it actually does the deletes. On rollback it undoes the deletes by reading the Log. The entire mechanics of this would have to change to do what you sre asking. It would have to simulate the entire transaction then check for integrity, then perform the transaction (holding locks on all the effected the records the entire time)

If you want to auto delete all the children, use cascading deleted. This is the only time you would ever delete the parent before the children.


答:
The database can not reorder the step of the transaction as it receives them in order.  It doesn't know you intend to delete from B when you requested deletions from A. However there two approaches to handling referential integrity within a transaction.  On Delete Cascade operation might solve your problem, but I prefer to limit their use.

There are two approaches to validation:

Immediate validation: Test the integrity as each action is performed.  This requires records be added in the proper order.  This seems to be the default setting for most databases.

Deferred validation: Test the integrity of the data when the data is committed.  This allows record to be added in any order.  On large transactions this can slow down commits. If you are adding datasets with circular references, deferred validation is required.

Some (most) databases may not support both validation approaches.  On some databases it may be possible to switch validation approaches on a per transaction basis.

Title: Is it possible (or desirable, if not) to make an database engine organize the order of sql statements to maintain the referential integrity?

Body:
Today at work I found the following situation:

We had two tables, A and B, with B having a foreign key linked to the primary key of A.

On our application, we got two main situations that created the problem :

One where we had to add add some records in A, followed by the creation of some records in B referring to the ones in A. This was just fine, since we created our BLL to handle first the changes in A and them B. The "problem" is, sometimes we will have to delete the records of B and them delete the referred record in A, wich raises an error, since we are trying to delete A before deleting B, what could break the referential integrity of these tables. Of course everything is inside a transaction, and we could deal with that in our BLL code, simply changing the order of wich changes cames first (in A or in B) based on the actions that have to be made, but my question is more conceptual than a "please help me solve my problem" one, since the "problem" is already solved (but of course, I'm accepting suggestions if they came up! =D).

Chatting in the office, we agreed that, inside a transaction, everything is being donne and if some problem occurs, what was done is rolled back.

My idea: Why can't the transaction evaluate everything and them order the statements and execute that in a way that don't break the referential integrity, since after the transaction everything will be done and the order might not matter at all? After thinking a little about it, even I am not sure if this thing would be nice or create some king of living hell, since I can think of some situations where the order of the statements would matter, so I'm posting it here so we can discuss about it.

I hope that my text is not confusing. And just to mention, I'm using Microsoft SQL Server. Dunno if this is possible in other databases.


答: There's always an entry point. For Java enterprise apps: servlets, filters, and context listeners are at the top, they normally lead into application bootstrapping e.g spring context loader, which then leads into controllers, then into entities and views. It's actually pretty straightforward, particularly if a framework such as spring, tapestry, or wicket is used. Once you know how the framework processes a request, you should be able to identify the extension points you need.</p>


问:
Are there any negative side effects of splitting up large modules?
I was browsing a github project and found this module which has more than 10 thousand lines.

Is it a common practice to have that much code in a single module?

It seems to me that this should be split over multiple modules. Maybe one for each db engine.

What benefit does the developer get from making one huge module like this (other than "having it all in one place") or what downside is there from splitting it up (other than "complexity")?

答:
This appears to be a module where typical size limits may not apply.   The majority of the functionality is in the first 2k lines of code and comments.  The rest of the file appears to be a lot of adapter classes and other support classes which appear to be tightly coupled to the module.  In other languages the classes would be in separate files of a reasonable size. </p>

<p>Some more doc strings might be useful, but they would increase the size of an already large module.  The code is clear and self explanatory with appropriate comments where needed. </p>

Body:
This appears to be a module where typical size limits may not apply.   The majority of the functionality is in the first 2k lines of code and comments.  The rest of the file appears to be a lot of adapter classes and other support classes which appear to be tightly coupled to the module.  In other languages the classes would be in separate files of a reasonable size.

Some more doc strings might be useful, but they would increase the size of an already large module.  The code is clear and self explanatory with appropriate comments where needed.


问:
What is meant by a primitive data type?
My understanding of a primitive datatype is that

It is a datatype provided by a language implicitly (Others are user defined classes)

So different languages have different sets of datatypes which are considered primitive for that particular language. Is that right?

And what is the difference between a "basic datatype" and "built-in datatype". Wikipedia says a primitive datatype is either of the two.

PS - Why is "string" type considered as a primitive type in SNOBOL4 and not in Java ?

答:
Why is "string" type considered as a primitive type in SNOBOL4 and not in Java ?

Because the Java Language Specification very clearly specifies what the word "primitive" means in the context of Java, and Java's String doesn't conform to this specification, whereas the SNOBOL4 Language Specification defines what "primitive" means in the context of SNOBOL4 and SNOBOL4's string conforms to that specification.

There's really nothing more to it. The specification of the respective language defines what certain words mean and something either fits that description or it doesn't. For example, the C Language Specification defines the meaning of the word "function" to be something which is very clearly not what the word "function" usually means, but that's the way the word is used inside the C community.

Title: What is meant by a primitive data type?


问:
Can you be Agile without doing TDD (test driven development)?
Is is possible to correctly call yourself (or your team) "Agile" if you don't do TDD (Test-Driven Development)?</p>

答:
Can you be Agile without doing TDD (test driven development)?

Short answer: Yes.

Longer answer:
There are a lot of really good answers already to this question and very good references.  I will not try to debate those points.

In my experience, Agile is about picking the right level of Lean-ness for the project at hand.  What do I mean by Lean-ness?  And, why do I bring it into this answer?

Lean does not mean chopping everything possible out of your method.  As one of our colleagues noted, you do not have to include TDD or Unit Test into your behaviors.  However, in the project context you find yourself, it may or may not be beneficial.

Let's think about the supply chain for a large unnamed retailer located in AK.  There is the consumer.  They go into the store.  The store receives various products via truck.  The trucks, presumably, get those products from a warehouse.  The warehouse is filled by shipments from various manufacturers.  The manufacturers in turn have whole chains of supply themselves.

What happens when the general manager for shipping in the above supply chain is told that he will get a $1 million annual bonus for every year that he has less than 10 trucks in the fleet?  He will immediate chop the fleet to 9 trucks.  In this "awful" scenario, this will drive up the amount of goods stored in the warehouse (driving up cost in that node).  And, it will "starve" the store fronts.

So, the overall supply chain suffers if local optimization is allowed without consideration of the whole.

Back to TDD and UT.  TDD is a requirements expression mechanism.  The system MUST perform to those constraints.  Fair enough.  TDD can replace Use Case Drive Development's requirements behavior or User Story Driven Development's requirements behavior.  It has the "leaning" benefit of combining the Unit Test and Requirements work loads.  It is a benefit if the overall work load is reduced.  It is not, if the overall supply chain's work load is increased (let's fix quality).

And so, you asked: Can you be Agile without doing TDD (test driven development)?

Sure you can.  A different, and perhaps better, question is:
-- If I apply TDD to this project, will it result in an overall more efficient delivery of software or a less efficient?

To quote a favorite author...  J.R.R. Tolkien

Lord of the Rings.  Fellowship of the Rings.  Pg 94
  'And it is also said', answered Frodo, 'Go not to the elves for counsel, for they will both no and yes.'

So, in the end, ...  it depends.  You must answer the question.  Which path will most efficiently lead you to your desired goal(s).

To TDD or not to TDD.  That remains the question.   :-)

PS - I am reposting this answer on another site too.
https://www.ibm.com/developerworks/mydeveloperworks/blogs/c914709e-8097-4537-92ef-8982fc416138/?maxresults=15&sortby=4&lang=en


答:
Static methods may be harder to test, but that doesn't mean you can't use them - you just need to set them up so that you don't need to test them.

Make both product.GetReviews and Review.ForProduct one line methods that are something like

```<code>new ReviewService().GetReviews(productID);
</code>```

ReviewService contains all the more complex code and has an interface that is designed for testability, but is not exposed directly to the user.

If you must have 100% coverage, have your integration tests call the product/review class methods.

It might help if you think about public API design rather than class design - in that context a simple interface with logical grouping is all that matters - actual code structure matters only to developers.

Title: SOLID vs. static methods

Body:
Here's a problem I frequently run into: Let there be a web shop project that has a Product class. I want to add a feature which allows users to post reviews to a product. So I have a Review class which references a product. Now I need a method that lists all reviews to a product. There's two possibilities:

(A)

```<code>public class Product {
  ...
  public Collection<Review> getReviews() {...}
}
</code>```

(B)

```<code>public class Review {
  ...
  static public Collection<Review> forProduct( Product product ) {...}
}
</code>```

From looking at the code, I'd choose (A): It's not static and it doesn't need a parameter. However, I sense that (A) violates the Single Responsibility Principle (SRP) and the Open-Closed Principle (OCP) whereas (B) doesn't:

(SRP) When I want to change the way reviews are collected for a product, I have to change the Product class. But there should be only one reason why to change the Product class. And that's certainly not the reviews. If I pack every feature that has something to do with products in Product, it'll soon be clattered.

(OCP) I have to change the Product class to extend it with this feature. I think this violates the 'Closed for change' part of the principle. Before I got the customer's request for implementing the reviews, I considered Product as finished, and "closed" it.

What is more important: following the SOLID principles, or having a simpler interface?

Or am I doing something wrong here altogether?

Result

Wow, thanks for all of your great answers! It's hard to pick one as official answer.

Let me summarize the main arguments from the answers:

pro (A): OCP is not a law and readability of the code matters as well.

pro (A): the entity relationship should be navigable. Both classes may know about this relationship.

pro (A)+(B): do both and delegate in (A) to (B) so Product is less likely to be changed again.

pro (C): put finder methods into third class (service) where it's not static.

contra (B): impedes mocking in tests.

A few additional things my colleges at work contributed:

pro (B): our ORM framework can automatically generate the code for (B).

pro (A): for technical reasons of our ORM framework, it will be necessary to change the "closed" entity in some cases, independently from where the finder goes to. So I won't always be able to stick to SOLID, anyway.

contra (C): to much fuss ;-)

Conclusion

I'm using both (A)+(B) with delegation for my current project. In a service-oriented environment, however, I'll go with (C).

Body:
Static methods may be harder to test, but that doesn't mean you can't use them - you just need to set them up so that you don't need to test them.

Make both product.GetReviews and Review.ForProduct one line methods that are something like

new ReviewService().GetReviews(productID);

ReviewService contains all the more complex code and has an interface that is designed for testability, but is not exposed directly to the user.

If you must have 100% coverage, have your integration tests call the product/review class methods.

It might help if you think about public API design rather than class design - in that context a simple interface with logical grouping is all that matters - actual code structure matters only to developers.


问:
The reason to make some code open source
I have a library that makes architecture to load data from server and display all controls in table layout. It works great but it have a lot of TODOs there.
Also, this library in 99% created by me. I starts developing it in when I working in one company, continue developing in in other company - I just move code prototype to new working place.
Library contain large amount of iPhone features/hacks/fixes that write again make no sense.
All created iOS business applications by me, based on this library.

When library become needed in few projects simultaneously, I wanted to make library open source on GitHub but my Team Lead ask to create private repository for it.
Library contains and uses 12 open source libraries.

So:

Is it a good idea to make such library open source? It contains all my iOS development experience.

How to argue my wish to make library open source for Team Lead?

If I can't make this library open source - can I use it in other company? In contract, thats I work with, said that I assign all copyrights to employer.

答:
Do this:

Encumber it and sell licenses (the old model) or open it and sell support (the new model)

Don't assume that you own any work that you're hired to do (so tuck your good ideas away).

Use your open source work to as it were, "earn your street credibility" (and massage your ego).

Exploit the enthusiastic community for free labor (as in Oracle doesn't care about MySQL).

Ask contributors to relinquish ownership of their works (to better screw the community later on).

Use a commercially-friendly liberal license like Apache, MIT, or BSD (since GPL is bad for business)

OwnerDisplayName: Yanny


问:
Do you have regularly schedule app updates? And if so how do you handle bugs that make it out?
We are trying to make our releases more frequent. As part of that we have blocked out a day of the week where we told users that we'll be doing updates. Similar how Microsoft has Patch Tuesday.

This is for a web app running completely server side, by the way. So updates are not a huge problem to deploy. Though they can get time consuming.

Occasionally an update has a bug that needs to be fixed before the next update window rolls around. I see two real options: either undo the update and restore a backup of the previous version, or make a fix and deploy it outside the scheduled time.

Making a fix sounds easy, but often times there are other changes that have been made to the code base. And the fix needs testing before it can realistically go out.

Rolling back isn't a bad option, but sometimes that will remove recent features or at least delay them until the next week.

答:
You seem to have a development problem. I know this because you said:

Making a fix sounds easy, but often times there are other changes that have been made to the code base. And the fix needs testing before it can realistically go out.

You need to isolate you production releases in your version control system (you are using one, right?).  Create a branch for your release.  Bugs that are discovered in the production release get fixed in that branch (and the fix merged back to the main development line).  Bugs that are fixed in main development have the fix brought into the branch if practical (or a parallel fix created if not).

This pretty much guarantees that fixes to the running production code will be tiny fixes, and easy to test (therefore quick to roll out if there's a problem), and hopefully makes them less disruptive.

Outside of that here's the best advice I can offer you:

Have some kind of internal test cycle.

Don't release code that doesn't work, or at least inflict it on a small set of users first.

(StackExchange uses meta.stackoverflow.com as their scratch monkey.)

Cut releases when you're reasonably confident they work

(The above-mentioned branching)

Fix bugs before adding features

(Liberally stolen from The Joel Test)

Don't be afraid not to release something if it's not ready.

Better not to ship a patch on "patch day" than to break the universe.

Don't be afraid to roll back something if it's not working.

(Corollary: Always have a back-out plan!)

Set a release schedule you can keep.

Once a week is HARD. Once a month is tough if you're doing more than bug-fixing. Once a quarter is pretty easy.

For reference, my company releases software the weekend following the 15th of every mid-quarter month (i.e. the weekend after February 15, May 15, August 15, November 15).  For various regulatory reasons our testing cycle is pretty rigorous, and this is as fast a pace as we can maintain while keeping software quality where we need it to be.

Emergency bug-fix patches are released as-needed, usually on Fridays (to give us a weekend where we have relatively low volume in case the fix breaks something else).

OwnerDisplayName: David Hogue


问:
Software markets for solo developer
I want to create something useful of my own which others can use it. This can be free or it can make a little money for sustaining its development and increase income little. However, when think about the market, I don't know what market is lacking applications, what types of domain can be possible for a solo developer or small development?

For example, I can develop small game for the smartphone market, with me as the programmer, another person is graphic designer and another person is music composer, to create a functional and playable game. Or what types of domain/market in web development are possible for a single developer to produce a web application?

Or should I include the forth person, business man to identify this for me? If you have experience on this, I would love and highly appreciate if you share for me and everyone.

EDIT: I want to do this as my part time job, not the main job until it's possible.

答:
I don't know if this helps, but over the years, I tend to write frameworks and libraries to automate most of my programming tasks in a certain technology, then I try and sell those when I discover that they are actually quite useful.

Another thing you can do is to surround yourself with young entrepreneurs. They are always coming up with ideas for businesses. You then architect a solution to solve one of their problems and voila, you're in business.

I am not that good at coming up with new ideas though.

Title: Software markets for solo developer


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
A new tool as a problem solver.

When people start planning to use unfamiliar tools, I don't mind, but I keep my eye on it.  When they start planning all the advertised benefits of those tools into the schedule, I get worried.  Fun examples:

We can shave a month of the schedule because we're going to try using an object oriented language (even though all we have are c developers).

We'll try out this new scrum thing- that'll fix all our process problems!

I know it's halfway through the project, but what if we changed ORMs to something new?

New technologies and practices are great, but you almost never get all the benefits out of the gate.


答:
You want a discussion, here you go.

Imagine a user at a website processing a purchase and instead of going through your step by step process of filling the shopping cart and processing the payment and shipping, they want to skip the credit card address information because you can just use the shipping address once they fill that in at the end. You demand they fill out the billing address first, but they just typed out that lengthy card number and need a break. Can't they just skip this address and enter an address later on? You can go back and get that address. Bill to the shipping or ship to the billing; does it really matter? I entered one address, obviously it applies to both.

Programmers can get frustrated working with databases because they do some things outside our control. They accomodate our needs for the most part, but there is always a situation where it doesn't obey. Your suggestion is instead of using the settings and capabilities to do exactly what you want in the database, you want to violate a simple rule, but have the database sort out your whole transaction just to see if there is a way it might work. Once all the options are exhausted, then you get an error.

If a transaction isn't going to work, wouldn't you rather know sooner than later? You can control what you send to the database, why not take advantage of that and program it accordinly?

Referential Integrity is enough of a performance issue, it doesn't need to act more intelligently to address a rule violation that could get a pass if it is handled within a transaction. Either setup the database to enforce the rules you want or don't have any rules and let your application handle it.

Many databases can optimize and establish a plan on the first request in hopes of performing better on subsequent requests. It's great when it works. What you are proposing could get complicated with more tables (i.e. a many-to-many situation) or nested transactions. Some simple things could get preplanned, but nothing too complex. Juat be thankful it processes the transactions in the order you sent them; it's saving you a debugging nightmare.


答:
Expanding on BillThor's answer, in Oracle at least, you can create deferrable constraints which are validated at commit time and then freely switch between having the constraint validated immediately and having it validated at the time you commit.

For example, I can create a parent table, a child table with a deferrable constraint, insert a row in the child that references a parent row that doesn't exist, and I don't get an error until I commit.

```<code>SQL> create table parent (
  2    parent_id number primary key,
  3    parent_name varchar2(100)
  4  );

Table created.

SQL> create table child (
  2    child_id number primary key,
  3    parent_id number references parent(parent_id)
  4                     initially deferred deferrable,
  5    child_name varchar2(100)
  6  );

Table created.

SQL> insert into child values( 10, 1, 'Child 1' );

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (SCOTT.SYS_C0017089) violated - parent key not
found
</code>```

If I create the parent after creating the child inside the same transaction, the commit succeds

```<code>SQL> insert into child values( 10, 1, 'Child 1' );

1 row created.

SQL> insert into parent values( 1, 'Parent 1' );

1 row created.

SQL> commit;

Commit complete.
</code>```

If I want the constraint to be enforced immediately instead, I can do that as well

```<code>SQL> ALTER SESSION SET CONSTRAINTS = IMMEDIATE;

Session altered.

SQL> insert into child values( 20, 2, 'Child 2' );
insert into child values( 20, 2, 'Child 2' )
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0017089) violated - parent key not
found
</code>```

or I can set the constraint back to beind deferred with the command

```<code>ALTER SESSION SET CONSTRAINTS = DEFERRED
</code>```

I would expect that other databases have similar functionality.

Body:
Expanding on BillThor's answer, in Oracle at least, you can create deferrable constraints which are validated at commit time and then freely switch between having the constraint validated immediately and having it validated at the time you commit.

For example, I can create a parent table, a child table with a deferrable constraint, insert a row in the child that references a parent row that doesn't exist, and I don't get an error until I commit.

SQL> create table parent (
  2    parent_id number primary key,
  3    parent_name varchar2(100)
  4  );

Table created.

SQL> create table child (
  2    child_id number primary key,
  3    parent_id number references parent(parent_id)
  4                     initially deferred deferrable,
  5    child_name varchar2(100)
  6  );

Table created.

SQL> insert into child values( 10, 1, 'Child 1' );

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-02091: transaction rolled back
ORA-02291: integrity constraint (SCOTT.SYS_C0017089) violated - parent key not
found

If I create the parent after creating the child inside the same transaction, the commit succeds

SQL> insert into child values( 10, 1, 'Child 1' );

1 row created.

SQL> insert into parent values( 1, 'Parent 1' );

1 row created.

SQL> commit;

Commit complete.

If I want the constraint to be enforced immediately instead, I can do that as well

SQL> ALTER SESSION SET CONSTRAINTS = IMMEDIATE;

Session altered.

SQL> insert into child values( 20, 2, 'Child 2' );
insert into child values( 20, 2, 'Child 2' )
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0017089) violated - parent key not
found

or I can set the constraint back to beind deferred with the command

ALTER SESSION SET CONSTRAINTS = DEFERRED

I would expect that other databases have similar functionality.


问:
Why choose an established CMS as opposed to building one from scratch?
A lot of my research over the next few weeks will be into different CMS's. I've already had a brief look at episerver and umbraco. While reading into these systems I can't help but think that providing content management features are achievable without learning the details and structure of many of these (rather large) CMS platforms.

I have, in the past, been given projects whereby my role as a developer must be kept separate to that of an editor (makes sense). i.e. It was my task to develop the design and functionality of the site and my clients' job to update the content. I've achieved this by also implementing a sort of 'portal' on which there were a couple of pages that would accept text input and picture uploads etc. (basically, whatever content they wanted), record this new content to the database and then by design the code-behind would read all this from the database into relevant controls (repeaters for example).

For me, this has been an effective enough way of my clients managing the content to deploy with my solutions. I know that I am wrong - and that CMS's are preferable to those that are built from the ground up - but other than the matter of cost, why?

答:
One thing needed to be factored is that your CMS may become obsolete, not necessarily in language, but rather functionality and design.  The next group of programmers may not want to work with those constraints in functionality and as far as design it may ruin their image!

If its a simple website, or you haven't much time to dedicate, CMS sounds great!

OwnerDisplayName: SkonJeet

OwnerDisplayName: HarHaHu


答:
You use an existing CMS to get rid of the weight of features that are probably important to the users that you don't want to have to keep track of.

EPiServer, Umbraco, Orchard, etc all have built in options for keeping track of things like versions, what content is linked to by other content, how to build forms, etc.  And beyond that they have events which you can hook to modify them as you see fit.

They typically have thousands of hours of troubleshooting already done, so why not take advantage of those.  Especially in the free or open source versions where it literally costs you nothing but the time learning their APIs which I can nearly guarantee is less time than you'd spend recreating that functionality.

So unless you don't need to rebuild the functionality they provide, why not use something already known to work well?

Here is just a brief list of features existing that you would not have to implement on your own:

content versioning

workflow

page link status reports

wysiwyg editor customization

content modeling (page types / document types)

content retrieval APIs

documentation / training for both editors and developers

object caching strategies

content querying systems for searching

content hierarchy structures (in CMS's where content is in a tree form anyway)

editor views

admin views

access control

Title: Why choose an established CMS as opposed to building one from scratch?

Body:
A lot of my research over the next few weeks will be into different CMS's. I've already had a brief look at episerver and umbraco. While reading into these systems I can't help but think that providing content management features are achievable without learning the details and structure of many of these (rather large) CMS platforms.

I have, in the past, been given projects whereby my role as a developer must be kept separate to that of an editor (makes sense). i.e. It was my task to develop the design and functionality of the site and my clients' job to update the content. I've achieved this by also implementing a sort of 'portal' on which there were a couple of pages that would accept text input and picture uploads etc. (basically, whatever content they wanted), record this new content to the database and then by design the code-behind would read all this from the database into relevant controls (repeaters for example).

For me, this has been an effective enough way of my clients managing the content to deploy with my solutions. I know that I am wrong - and that CMS's are preferable to those that are built from the ground up - but other than the matter of cost, why?

OwnerDisplayName: sparks


答:
The number one reason for creating your own CMS is to be able to add your own functionality to it over time. With an off-the-shelf CMS you are tied to the architecture and technology of the third party who created it.

Examples:

Umbraco - reliance on XSLT for layout - #fail

Orchard - over-engineered and learning curve for Web Forms devs

...etc.

OwnerDisplayName: IrishChieftain


答:
There's NO definitive answer as to which ones better. It depends on your needs, structure, cost, man power, and any number of other factors.

Pre-made/established CMS

Pros

Saves A LOT of time. Some of the CMS' that have been around for years have lots and lots of man hours into them. You may not need 10% of the features in a pre-made CMS, but regardless it saves time and time is not free!

Saves A LOT of money.

Generally have a HUGE amount of features that will probably work for your needs.

Cons

License. You need to abide by the license of the pre-made CMS you use. This may not be a big deal, but maybe you want to change something prohibited by the license, or maybe you'll be prohibited from using it in a production environment.

Heavy. Since the CMS will most likely be tailored to reach as many audiences as possible. Maybe you have a server limitation or don't want to load excess scripts for basic content management.

Possibly written in a non-modular fashion. Lets say you implemented a pre-made CMS and the website is done ready for the client to sign off and say let's deploy! Then you shoot it over to your client and they say "Oh, I want to add this feature to the CMS!" Then, if you chose a CMS that is very complex or not very modular you may have a problem implementing their feature request or it may take an excessive amount of time.

Inherit their bugs. You will inherit all existing bugs on the CMS. It's not a problem since they're usually easy to update, but what if you heavily modified parts of it to add a feature?

Home-brewed/custom CMS

Pros

Tailored to your needs. You will be able to integrate ONLY what you need and retain high portability.

Written in your language. Maybe you have an ASP.net MVC website and all the CMS' out there are written in PHP, but you want one that is written in C# using MVC and the razor view engine (idk random example). It's much easier to maintain a web page that is uniform and doesn't have a huge PHP/JS/etc. CMS in the midst of all the C# code.

Yours you/your company own it 100%, you can use it in as many applications as you want w/o buying additional licenses, etc.

Cons

Time-consuming, therefore it's expensive. You could spend any amount of time 1-Dozens of days working on a CMS depending on hours put in, experience, etc, etc.

If you have the time, and none of the pre-made systems fit the bill or are way too complex i see no reason not to build your own, other than the time-consuming factor of course.

OwnerDisplayName: bbedward


答:
You might want to add web security to the discussion too. If you build a CMS from scratch, chances are you will have vulnerabilities to a number of attacks (see e.g. https://www.owasp.org/index.php/Top_10_2010-Main). If you on the other hand use an existing CMS, it will generally be more secure, but on the other hand its vulnerabilities will be more widespread.

So it's a bit of a tradeoff securitywise, but I would argue that a well-updated "standard" CMS is more secure than a home-made one, but it to some extent depends which of the standard ones you choose.

However, if you use a "standard" CMS and do a lot of modifications, you might break the upgrade path and end up with not being able to update your CMS and thus you are vulnerable.

OwnerDisplayName: Magnus H


问:
What are benefit/drawbacks of classifying defects during a peer code review
About 3 months ago, our engineering group rolled out Review Board to be used for all peer code reviews.  Today, I had a discussion with one of the people involved in that process and found out that we are already looking for a replacement (possibly something commercial) because of several missing features.

One of the features that is apparently asked by many people is the ability to classify/categorize each code review comment (i.e. is it a style issue, coding convention, resource leak, logic error, crash... whatever).

For those teams that regularly practice code review, is this categorization a common practice? Do you do it? have you done it in the past? Is it good/bad?

On one hand, it gives the team some more metrics and possibly will indicate more specific areas where developers may potentially need to be trained in (at least that seems to be the argument).  Are there other benefits?  And on the other hand, and this is my concern, is that it will slow down code review process that much more.  As a team lead, I've done a fairly large share of reviews, and I've always liked the ability, to highlight a chunk of code, hammer off a comment and move on as fast as possible.  Although I haven't tried it personally, I have a feeling that expanding that combo box every time and scrolling/searching for the right category would feel like something is tripping you. Also if we start keeping metrics on this stuff, my other concern is that valuable code review meeting time will be spent on arguing whether something is a logic error or if it should be classified as a crash.

答:
...on the other hand, and this is my concern, is that it will slow down code review process...

If you want to keep reviews lightweight then effort consuming stuff like investigation, fixes and testing for discovered defects shouldn't be there.

Straightforward (dumb if you wish) option to handle that is, well, just drop it and wait until testers find and report the bug themselves. The major drawback of this approach is that some problems that are easily visible in source code may take much efforts to discover in black box testing.

Threading issues and memory leaks often fall in this category. Data race that takes me a minute to detect by looking at code, may sit there for months, passing all the tests before it rears its ugly head.

Because of above, I never use and don't recommend an option like above.

Another option is to dequeue heavy work - in the sense that it goes of my reviewer working queue somewhere else. This option is one I use, the one I am quite comfortable with.

The approach is quite simple. If I feel that problem(s) I found may take substantial effort to deal with, I simply create a ticket in issue tracker with title like "investigate and address issues pointed out in code review <review ID / URL>" and keep on going through code making comments in a free form. I don't waste time on stuff that will be done per ticket I opened - because it will enter team work queue and be prioritized and dealt with in a routine way.

That way, I make sure that 1) review process remains as lightweight as possible and 2) problems discovered won't be forgotten.


问:
Migrating from Python to Scala wise when a lot of work is already done in Python?
Me and my friend are developing a web-app in Python + Flask + PostgreSQL. We have been working on it for the past few months and have developed a lot of schema/use-cases specific to Python + Flask + PostgreSQL. Now, all of a sudden, we plan to move to another NoSQL database (Neo4j) because it somehow fits better to what the core of our web-app is going to be. Python supports Neo4j through embedded/rest api bindings, but uses a technology JPype, which is rather unmaintained, to say the least.

So, this question of using Scala arose today. Ours is going to be next-to-realtime application, so we can't afford to have the lag/overhead of having intermediate steps of Python->Java requests (Neo4j standalone server is based on embedded Neo4j). So, whereas I am in favour of spending a month or two and learning Scala/Lift, he is in favour of carrying on with Python and porting to Scala whenever need arises, even though when we know that Python+bindings will be a bit slower as compared to the native Neo4j support for Java.

In the past few months, we had done a lot of work in Python + Flask + PostgreSQL already. If we port to Scala, we will need to port all of it to Scala.

Would it be wise to port now? Are there any personal experiences or advices from you all? Or is this just premature optimization?

P.S.: I am aware of the learning curve of Scala/Lift.

答:
Obviously you're not going to get a definite answer here, because it really depends on your individual case and, in particular, who's working on the project. I'm not sure what you intend to gain though, but it sounds like you would have to throw away a lot of work.

Scala is slightly more buzzword-compliant these days, but Python is no slouch when it comes to functional programming either. Still, it all depends on the specifics of your workload.

Just remember Knuth's advice about premature optimization; he's a pretty bright guy. I'd say if you're even remotely close to finishing, then don't change. It's far more important to get some working code as quickly as possible than to "do it right" the first time. Because you simply don't know what you will have done wrong until you can test it.

Then, once you know what your choke points are, design something that addresses your real concerns.


问:
What are hooks?
I keep coming across this term hooks in various programming articles. However I don't understand what they are, and how can they be used. So I just wanted to know what is the concept of hooks; if someone could link me to some examples, particularly in the context of web development, it would be great.</p>

答:
Depending on the background of the person asking sometimes the answer to this question can be as simple as hooks are usually another word for an event handler, which Blaenk gave an excellent explanation for.

There are also uses of this phrase that are when you inject an event or code into a process that otherwise does not have events like moles for example.

Title: What are hooks?

ContentLicense: CC BY-SA 4.0


答:
Of course the actual "limit" varies by your project and a multitude of factors.

But I chime in with a rule of thumb: 200 lines of decent Python. That is, no C or Java code written in Python, but good Python in Python.

Title: Are there any negative side effects of splitting up large modules?

Body:
I was browsing a github project and found this module which has more than 10 thousand lines.

Is it a common practice to have that much code in a single module?

It seems to me that this should be split over multiple modules. Maybe one for each db engine.

What benefit does the developer get from making one huge module like this (other than "having it all in one place") or what downside is there from splitting it up (other than "complexity")?


问:
Agile development : How to design your code for an iteration / Sprint?
In Agile development you work on small user stories and produce a working iteration.

But what happens when the next user story comes in and affects the design for the already done iteration?

Sometimes it seems like re-doing the last iteration or another user story to incorporate the new user story in the last iteration!

How to approach on this?

答:
As there seems to be a bit of debate on where exactly the question is heading, I'll try to give a few pointers:

In non-agile process models you typically have changes being made to requirements, which roughly corresponds to your scenario. In that case, the effects are especially easy to see when you consider the waterfall model: you have to go through your whole product and all previous process steps in order to adjust for the new or changed requirement.

In Agile development, before you start your sprint you should have a meeting to discuss which user stories/epics/features/.. you plan to realize in the upcoming sprint along with an estimation of the required efforts. It is this latter emphasized part, where you as a team member should raise the bar significantly if you see that a major design change and lots of refactoring will be required.

Everything becomes more problematic, the less competent the team is of course. So, if you get told a user story and you say you can implement it in 2 weeks, but only later come to realize that you need to redesign and it'll take you at least 4 weeks, it is too late. You will already be mid-way in the sprint and the sprint will fail. At this point, the only option pretty much is to cancel the sprint right-away. You re-start at that point by having a new meeting and look at the user stories you want to realize in the then next sprint including your new knowledge of the design problems, which will lead to more accurate time estimates.

To finish with a more positive statement than that: It does help enormously to rely on good time estimation methods (f.ex. planning poker) in order to reduce the risk of estimates going way off.

To extend the answer with regards to your comment: Code quality ensurance remains basically unchanged by this. You ensure code quality by testing, and you do so no matter if you have to redesign or not. Of course, a chair cannot be cast into a table. But this simply means, that you have test cases which try to do that, but fail. This is actually the easy case (because the failure pops up easily when you run your tests), in which your test no longer matches the updated design. Do not forget that the process of redesigning involves updating your existing tests. If requirements change, your old tests cannot be trusted anymore!

Here are a few pointers to articles specifically on testing in an Agile context.


问:
How much AJAX is too much?
My current project is part of a highly linked architecture, with individual systems each owning certain pieces of data, and exposing them RESTfully. Both our web services and our user interface take advantage of this linkage, storing links to the resources in other systems rather than storing a copy of the data, and presenting composite views by fetching the current state of those resources.

For example, my system might be responsible for a yearbook of people (I'm not using our real data and relationships here, of course). People are owned by another system, and perhaps have contact information (email addresses, phone numbers, twitter handles, etc). That contact information might be stored in another system that has details about the phone number or email address.

In order to present a view in my user interface, I then have to fetch my own data and follow the links in order to present the appropriate details from these other systems. I could cache certain parts of this information but likely want to retrieve the newest details.

In some of my pages, I have a reasonably small number of lookups to do this kind of data enrichment. In other pages, I am presenting a lot more information and end up with an explosion of data as I get a list, expand each element, expand each of those, and so on. I have experimented with providing a service which does this aggregation and returns all the data needed by the view in a single response. However, I am not sure whether this is the cleanest way to provide this.

Can anyone suggest some strategies for determining when I should directly use AJAX requests to fetch this data? At what point should I switch from individual requests to providing aggregated services to build the data? Or is there some other technique I could apply?

答:
I've found that developers familiar with ASP .NET Web forms and code-behind simply replace their code-behind with javasctipt and Ajax. They tend to put an Ajax onclick behind the smallest of user controls, which is effectively a server control event handler.

You have to understand what the consequences of making an Ajax call are. For example, if the call is going to result in a call to some WCF/EJB and onto a datastore then that call will span 4 processor boundaries (browser, Web Svr, App Layer, DB). These calls are expensive in terms of the latency involved in preparing the call and marshaling data.

Ajax promotes fine grained remote processing which is actually an anti-pattern according to Martin  Fowlers Service Facade. Like anything, Ajax is fine in moderation and in the right place. I don't think that place is in commercial software.

Title: How much AJAX is too much?


问:
Your experience with haxe and other languages that compile to PHP?
I would like to hear opinions from people who have used a language that compiles to php. One such language I know is Haxe. Other ones I've read about are Kira and Pharen.

How well do these languages integrate with PHP? Is it relatively easy to write a plug-in for a PHP CMS in them?

How mature are their implementations and tools?

Would you recommend them to someone who has to use a php cms but hates php?

答:
If it's to make a plugin for a PHP CMS, stay with PHP.

Although I use HaXe and finds it really really great, I do not recommend it in this case. It's simply too many indirections and the costs would be higher than the gains for just a small plugin.


问:
Are operators clearer to read than keywords or functions?
It's a bit subjective, but I'm hoping to get a clearer understanding of what factors make an operator clear to use vs obtuse and difficult.  I've been considering language designs recently, and one issue that I always circle back around on is when to make some key operation in the language an operator, and when to use a keyword or function.

Haskell is somewhat notorious for this, as custom operators are easy to create and often a new data type will come packaged with several operators for use on it.  The Parsec library, for example, comes with a ton of operators for combining parsers together, with gems like >. and .>  I can't even recall what they mean right now, but I do remember them being very easy to work with once I had memorized what they actually mean.  Would a function call such as leftCompose(parser1, parser2) have been better?  Certainly more verbose, but clearer in some ways.

Operator overloads in C-like languages are a similar issue, but conflated by the additional problem of overloading the meaning of familiar operators like + with unusual new meanings.

In any new language, this would seem like a pretty tough issue.  In F#, for example, casting uses a mathematically derived type-casting operator, instead of the C# style cast syntax or the verbose VB style.  C#: (int32) x VB: CType(x, int32) F#: x :> int32

In theory a new language could have operators for most built-in functionality.  Instead of def or dec or var for variable declaration, why not ! name or @ name or something similar.  It certainly shortens up declaration followed by binding: @x := 5 instead of declare x = 5 or let x = 5  Most code is going to require a lot of variable definitions, so why not?

When is an operator clear and useful, and when is it obscuring?

答:
I suppose the most extreme example is APL the following program is the "game of life":

```<code>life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
</code>```

And if you can work out what it all means without spending a couple of days with the reference manual then good luck to you!

The problem is you have a set of symbols that nearly everyone intuitively understands:  +,-,*,/,%,=,==,&

and the rest which require some explanation before they can be understood, and, are generally specific to the particular language. For instance there is no obvious symbol to specify which member of an array you want, [],() and even "." have been used, but equally there is no obvious keyword you could easily use, so there is a case to be made for judicious use of operators. But not too many of them.

Body:
I suppose the most extreme example is APL the following program is the "game of life":

life←{↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}

And if you can work out what it all means without spending a couple of days with the reference manual then good luck to you!

The problem is you have a set of symbols that nearly everyone intuitively understands:  +,-,*,/,%,=,==,&

and the rest which require some explanation before they can be understood, and, are generally specific to the particular language. For instance there is no obvious symbol to specify which member of an array you want, [],() and even "." have been used, but equally there is no obvious keyword you could easily use, so there is a case to be made for judicious use of operators. But not too many of them.


答:
Currently I'm working on an application that uses the ExtJS framework and there is AJAX everywhere. Launching a module of the application and loading a report causes up to 30 AJAX requests.

Once you get used to the idea that AJAX is a normal part of your software development, you just stop counting. AJAX is nothing that has to be limited or avoided.

Just make sure you don't get race conditions when processing the output of one AJAX call depends on the output on the other.

Title: How much AJAX is too much?

Body:
My current project is part of a highly linked architecture, with individual systems each owning certain pieces of data, and exposing them RESTfully. Both our web services and our user interface take advantage of this linkage, storing links to the resources in other systems rather than storing a copy of the data, and presenting composite views by fetching the current state of those resources.

For example, my system might be responsible for a yearbook of people (I'm not using our real data and relationships here, of course). People are owned by another system, and perhaps have contact information (email addresses, phone numbers, twitter handles, etc). That contact information might be stored in another system that has details about the phone number or email address.

In order to present a view in my user interface, I then have to fetch my own data and follow the links in order to present the appropriate details from these other systems. I could cache certain parts of this information but likely want to retrieve the newest details.

In some of my pages, I have a reasonably small number of lookups to do this kind of data enrichment. In other pages, I am presenting a lot more information and end up with an explosion of data as I get a list, expand each element, expand each of those, and so on. I have experimented with providing a service which does this aggregation and returns all the data needed by the view in a single response. However, I am not sure whether this is the cleanest way to provide this.

Can anyone suggest some strategies for determining when I should directly use AJAX requests to fetch this data? At what point should I switch from individual requests to providing aggregated services to build the data? Or is there some other technique I could apply?


问:
How do I dive deep into code that does not have a single entry point?
I work on enterprise Java projects that do not have a single entry point from where I can trace the flow of execution. Some of the projects have hundreds of classes, and when I'm asked to add a feature to a project, I often find myself at a loss as to where to start looking at code.

What's the best way to dive into such projects so that I can implement the feature quickly without wasting time.

答:
This is almost impossible to extend your java project if you don't get the entry points and a clear documentation of what has been done and why.

FYI: When we deliver a project to our customers we now systematically join an UML model as well as java doc and a printed documentation. We create hundreds of views from the model displayed as class diagrams. We add plenty of comments and explain the static architecture as well as business rules and methods flow. If our customers want to take his code and give it to another company it will be easy for them to modify the existing software not only at deployment level but also at architecture level. Powerful, simple and brilliant use of dynamic UML views from a single model.

Having said that I know very few integrators interested to provide all this information because once the customer is trapped it is better not to let him go. Giving full model and dynamic UML navigation will allow customers to be independent and therefore this is not good for business revenue. I still don't understand why big banks, or telecom companies are so naive to get trapped by integrators and don't ask the full model at the project delivery ? The java code or a printed documentation is not enough. The printed documentation is usually an automatic process. It has no real value to extract information from the code in order to print it or provide a PDF.


问:
REST - Tradeoffs between content negotiation via Accept header versus extensions
I'm working through designing a RESTful API.  We know we want to return JSON and XML for any given resource.  I had been thinking we would do something like this:

```<code>GET /api/something?param1=value1
Accept:  application/xml (or application/json)
</code>```

However, someone tossed out using extensions for this, like so:

```<code>GET /api/something.xml?parm1=value1 (or /api/something.json?param1=value1)
</code>```

What are the tradeoffs with these approaches?  Is it best to rely on the accept header when an extension isn't specified, but honor extensions when specified?  Is there a drawback to that approach?

答:
@vartec: I think you are wrong

The proper official RESTful principle says nothing should be hidden in HTTP headers as it is the URI which is exposed or referenced, any detail about the request/response should be provided as part of URI

Hence i strongly recommend to avoid using header for details which about the request & response, and stick to

```<code> GET /api/something.xml?parm1=value1 (or /api/something.json?param1=value1)
</code>```

I am not able to find the references quickly, but i will post back with them (actually you could refer the O'reilly publication book "RESTful web services" (http://shop.oreilly.com/product/9780596529260.do) which confirms the same

Body:
@vartec: I think you are wrong

The proper official RESTful principle says nothing should be hidden in HTTP headers as it is the URI which is exposed or referenced, any detail about the request/response should be provided as part of URI

Hence i strongly recommend to avoid using header for details which about the request & response, and stick to

 GET /api/something.xml?parm1=value1 (or /api/something.json?param1=value1)

I am not able to find the references quickly, but i will post back with them (actually you could refer the O'reilly publication book "RESTful web services" (http://shop.oreilly.com/product/9780596529260.do) which confirms the same


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
Another reason why use semicolon is because it is one of the characters which we do not require or use more often.

Assume we use it more often as a variable name or some thing and if semicolon would have been used as a keyword or as a operator, it would have been a symbol conflict for the compiler, hence it was important to use a symbol which is not often used in the coding.

I believe C style programming languages made it popular and then authors of new programming languages do not wanted to reinvent the wheel and they continued using it, till now.


问:
Is it a good idea to do UI 100% in Javascript and provide data through an API?
My primary day job is making HTML applications. With that I mean internally used CRUD-type applications with lots of editable gridviews, textboxes, dropdowns, etc. We're currently using ASP.NET webforms, which do get the job done, but the performance is mostly dismal, and quite often you have to jump through hoops to get what you need. Hoops which are hung from the ceiling and set aflame.

So I'm wondering if it perhaps would be a good idea to move all UI to the JavaScript side. Develop a strong set of reusable controls which are tailored specifically to our needs, and only exchange data with the server. Yes, I like the "control" (aka "widget") paradigm, its quite well suited to such applications. So on the server side we would still have a basic layout simliar to our current ASPX markup, but that then would get sent to the client only once, and the Javascript part would take care of all the subsequent UI updates.

The problem is I've never done this before, and I've never seen anyone doing this either, so I don't know what the problems would be. In particular, I'm worried about:

Performance still. Benchmarking shows that currently the main delay is on the client side, when the browser tries to re-render most of the page after an AJAX update. ASP.NET webforms generated markup gives a new meaning to the word "web", and the rich Devexpress controls add their own layer of Javascript complexity on top of that. But would it be faster to recalculate all the necessary changes on Javascript side and then update only what needs to be updated? Note that I'm talking about forms that have several editable gridviews, lots of textboxes, many dropdowns each with half-a-zillion filterable items in them, etc.

Ease of development. There would be a lot more Javascript now, and it would probably mix with the HTML markup of the page. That or some kind of new view engine would have to be produced. Intellisense for Javascript is also a lot worse than for C# code, and due to the dynamic nature of Javascript it can't be expected to get a lot better. Coding practices can improve it a bit, but not by much. Also, most of our developers are primarily C# developers so there will be some learning curve and initial mistakes.

Security. A lot of security checks will have to be done twice (server-side and UI-side), and the data-processing server side will have to include a lot more of them. Currently, if you set a textbox to be read-only on server side, you can depend on its value not changing through the client roundtrip. The framework already has enough code to ensure that (through viewstate encryption). With the data-only approach, it gets harder, because you have to manually check everything. On the other hand, maybe security holes will be easier to spot, because you will have only data to worry about.

All in all, will this solve our problems, or make them worse? Has anyone ever attempted this, and what were the results? Are there any frameworks out there that help in this sort of endeavor (jQuery and moral equivalents aside)?

答:
Yes you can but..

You need to make sure you have graceful "degradation" so that critical parts of your application will still work without Javascript.

This is how I build most apps "HIJAX" style.


答:
Linkedin do this for their mobile site (see http://engineering.linkedin.com/nodejs/blazing-fast-nodejs-10-performance-tips-linkedin-mobile part 4), and it's apparently been very beneficial for them from a performance standpoint.

However, I'd suggest you avoid doing the same, for various reasons.

The first is maintainability: C#/ASP.net is, due to it being a server-side framework, client-independent, whereas Javascript is not (even with a framework like jQuery you're not going to get 100% cross-browser compatibility, not future-proofing). I'd say it's also easier to verify the functionality of a statically-typed application than an dynamic one, which is something you absolutely must consider if you're building large-scale sites.

The second is that you're going to find it difficult to find other people who are capable (and willing) to build a pure-javascript application of the kind of complexity needed to run your entire website (compared to the relative ease of finding .NET programmers). This might not be a concern of yours directly, but it certainly is something to think about from a long-term perspective.

The third issue is client-compatibility; if you're building public-facing websites then remember that a reasonable portion of the net still does not have JS enabled (for various reasons), so you'll need to be absolutely sure that you're not going to exclude a large portion of your userbase by switching to a JS-driven website.

As for your bulleted concerns:

I wouldn't worry too much about the security aspect, there's no reason why you could not mix paradigms and do some server-side processing when you require security (you're going o have some view-rendering code in there somewhere that returns HTML, there's no reason you can't have this just fire off an AJAX call instead, when required).

Ease of development isn't really a concern too, in my opinion, there are very good tools available for JS development, don't just box yourself into VisualStudio because you're used to it! (try JetBrains WebStorm, for example).

Performance of JS view engines is absolutely fine in most cases (again, in my experience), I use them heavily on a day-to-day basis. What I would suggest is avoiding the more heavyweight frameworks like knockout.js etc., and head instead for something like Jon Resig's micro template engine. This way you can plug in the supporting code in ways you're confident are fast and reliable.

What I'd do, if I were you, is really examine the reasons behind this switch; It could well be that you're just not leveraging .NET effectively and need to up your game, WebForms isn't a particularly slow framework out-of-the-box, so perhaps some of the 3rd-party libraries you're using are slowing down your rendering.

Try doing a performance profile of the application using a load test and profiling tool, and see where your bottlenecks are before you sink a large amount of time and effort into a more radical solution, you'll probably be surprised at what you find as the culprit for your slowness!

Title: Is it a good idea to do UI 100% in Javascript and provide data through an API?

Body:
My primary day job is making HTML applications. With that I mean internally used CRUD-type applications with lots of editable gridviews, textboxes, dropdowns, etc. We're currently using ASP.NET webforms, which do get the job done, but the performance is mostly dismal, and quite often you have to jump through hoops to get what you need. Hoops which are hung from the ceiling and set aflame.

So I'm wondering if it perhaps would be a good idea to move all UI to the JavaScript side. Develop a strong set of reusable controls which are tailored specifically to our needs, and only exchange data with the server. Yes, I like the "control" (aka "widget") paradigm, its quite well suited to such applications. So on the server side we would still have a basic layout simliar to our current ASPX markup, but that then would get sent to the client only once, and the Javascript part would take care of all the subsequent UI updates.

The problem is I've never done this before, and I've never seen anyone doing this either, so I don't know what the problems would be. In particular, I'm worried about:

Performance still. Benchmarking shows that currently the main delay is on the client side, when the browser tries to re-render most of the page after an AJAX update. ASP.NET webforms generated markup gives a new meaning to the word "web", and the rich Devexpress controls add their own layer of Javascript complexity on top of that. But would it be faster to recalculate all the necessary changes on Javascript side and then update only what needs to be updated? Note that I'm talking about forms that have several editable gridviews, lots of textboxes, many dropdowns each with half-a-zillion filterable items in them, etc.

Ease of development. There would be a lot more Javascript now, and it would probably mix with the HTML markup of the page. That or some kind of new view engine would have to be produced. Intellisense for Javascript is also a lot worse than for C# code, and due to the dynamic nature of Javascript it can't be expected to get a lot better. Coding practices can improve it a bit, but not by much. Also, most of our developers are primarily C# developers so there will be some learning curve and initial mistakes.

Security. A lot of security checks will have to be done twice (server-side and UI-side), and the data-processing server side will have to include a lot more of them. Currently, if you set a textbox to be read-only on server side, you can depend on its value not changing through the client roundtrip. The framework already has enough code to ensure that (through viewstate encryption). With the data-only approach, it gets harder, because you have to manually check everything. On the other hand, maybe security holes will be easier to spot, because you will have only data to worry about.

All in all, will this solve our problems, or make them worse? Has anyone ever attempted this, and what were the results? Are there any frameworks out there that help in this sort of endeavor (jQuery and moral equivalents aside)?


问:
How do you find time to work on Open Source Projects?
A bit of background: I've got a small open source project that I've started on, a basic framework which provides an object oriented means of generating HTML code (since I don't really like HTML, and I do like PHP). It has some released source, and a few downloads, but primarily, the project is for me, with the Open Source portion just being a side benefit.

The original project which caused me to be able to develop on this project has mostly gone into hibernation for the time being, which means that all the development I get to sink into it at this point is personal time only. Unfortunately, I'm currently working toward my bachelor's degree, studying for certifications, and I have a three month old baby at home. In short, by the time I get around to "me time", I rarely feel like doing work, but rather usually feel like just chilling out.

So, if there's anyone else out there who feels like they're in a similar position, what strategies have you used to keep yourself motivated toward working on the project? I would really like to at least be able to work on this until I have 100% spec coverage, but I haven't committed source in months. Anyone out there who can help?

答:
Most people have a fair amount of downtime that they use watching television.  (This doesn't normally apply to parents of three-month-olds.)  It isn't generally a matter of finding time, but finding energy and motivation.

Are you usually able to sleep through the night?  I wasn't when my kid was that old.  If you're not getting enough sleep, you're going to have a hard enough time with your schoolwork, let alone an outside project.

So, spend time with your wife and kid.  Don't worry about extra projects for now, there will be more time for that a few years from now.


答: Use ExtJS if you want to go that way, don't reinvent the wheel. But be prepared, this means a complete paradigm change. You HTML skills are nearly obsolete. AJAX everywhere, the server mostly provides an AJAX API. You will write a lot more javascript than ever, so better make sure you are really fit with javascript.</p>


答:
The problem you describes is related to YAGNI.

In pure agile mindset you can follow YAGNI and code exactly what current user story demands without any upfront decisions about further needs of your code. It can really end with the problem you describe.

In pragmatic way you can look into your backlog and priorities of other known user stories and somehow reflect further needs in your current implementation. It doesn't mean that you will code your current stories with features required for future stories but you will lay the design of current implementation to be extensible for expected needs.

In contrast YAGNI is still in the game in case of unknown future requirements. If your backlog doesn't contain high prioritiezed story demanding some significant changes in your current implementation you will simply code your current implementation in the simplest possible way to fulfill just the current story. The reason is avoiding gold plating of your code = delivering something nobody really wanted.

Conclusion: If you can predict what happens next (items in your backlog are mostly stable) you can add such decisions to your current implementation. If you cannot predict what will be needed in future simply follow YAGNI.

Title: Agile development : How to design your code for an iteration / Sprint?

Body:
In Agile development you work on small user stories and produce a working iteration.

But what happens when the next user story comes in and affects the design for the already done iteration?

Sometimes it seems like re-doing the last iteration or another user story to incorporate the new user story in the last iteration!

How to approach on this?


答:
Semicolon was originally proposed in Algol 60 as a statement separator, not a terminator.

Prior to Algol 60, the only high-level programming language in existence was Fortran, which required each statement to be on a separate line.  Statements spanning multiple lines, like do-loops, were considered an oddity, and they were regarded as 'statement blocks'.

The designers of Algol 60 realized that statements needed a hierarchical structure (if-then-else, do-loops, case statements etc) and they could be nested inside each other.  So, the idea of each statement sitting on a separate line didn't make sense any more.  Sequential composition of statements of the form S1; S2; ...; Sn optionally enclosed in begin - end brackets were called compound statements, and fit into the hierarchical structure of statements envisaged by Algol 60.  So, here, the semicolon is clearly a statement separator, not a terminator.

This gave rise to problems in practice.  Algol 60 also had an "empty statement" which was denoted by writing nothing.  So, one could write "begin S1; end" where the semicolon appears as if it is terminating S1.  But the Algol 60 compiler really treated it as a separator between S1 and an invisible empty statement following it.  These subtleties were a bit much for practical programmers.  Having been used to line-oriented languages like Assembly and Fortran, they really thought of semicolon as a terminator for statements.  When programs were written out, usually semicolon was put the at the end of the statements, like so:

```
    a[i] := 0;
    i := i+1
```

and the semicolon really looked like a terminator for the first statement.  If the programmers treated the semicolon as a terminator, then statement like this would give a syntax error:

```
    if i > 0 then
      a[i] := 0;
    else
      a[i] := 1;
```

because the semicolon terminates the "if" and, so, the "else" becomes dangling.  Programmers were thoroughly confused.

So, PL/I, which was the IBM's successor to line-oriented Fortran, decided to make the semicolon a statement terminator rather than a separator.  Programmers were happy with that choice.  The majority of programming languages followed suit.  (Pascal resisted the trend, but its successor Ada gave up on it.)

[Note added: Wikipedia article on programming language comparisons has a nice table summarizing how semicolon is treated in various programming languages.]

Title: Why are statements in many programming languages terminated by semicolons?

Body:
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

Body:
Semicolon was originally proposed in Algol 60 as a statement separator, not a terminator.

Prior to Algol 60, the only high-level programming language in existence was Fortran, which required each statement to be on a separate line.  Statements spanning multiple lines, like do-loops, were considered an oddity, and they were regarded as 'statement blocks'.

The designers of Algol 60 realized that statements needed a hierarchical structure (if-then-else, do-loops, case statements etc) and they could be nested inside each other.  So, the idea of each statement sitting on a separate line didn't make sense any more.  Sequential composition of statements of the form S1; S2; ...; Sn optionally enclosed in begin - end brackets were called compound statements, and fit into the hierarchical structure of statements envisaged by Algol 60.  So, here, the semicolon is clearly a statement separator, not a terminator.

This gave rise to problems in practice.  Algol 60 also had an "empty statement" which was denoted by writing nothing.  So, one could write "begin S1; end" where the semicolon appears as if it is terminating S1.  But the Algol 60 compiler really treated it as a separator between S1 and an invisible empty statement following it.  These subtleties were a bit much for practical programmers.  Having been used to line-oriented languages like Assembly and Fortran, they really thought of semicolon as a terminator for statements.  When programs were written out, usually semicolon was put the at the end of the statements, like so:

    a[i] := 0;
    i := i+1

and the semicolon really looked like a terminator for the first statement.  If the programmers treated the semicolon as a terminator, then statement like this would give a syntax error:

    if i > 0 then
      a[i] := 0;
    else
      a[i] := 1;

because the semicolon terminates the "if" and, so, the "else" becomes dangling.  Programmers were thoroughly confused.

So, PL/I, which was the IBM's successor to line-oriented Fortran, decided to make the semicolon a statement terminator rather than a separator.  Programmers were happy with that choice.  The majority of programming languages followed suit.  (Pascal resisted the trend, but its successor Ada gave up on it.)

[Note added: Wikipedia article on programming language comparisons has a nice table summarizing how semicolon is treated in various programming languages.]


问:
What's the role of a Project Manager in Scrum?
What's the role of a Project Manager in Scrum?

I have heard that it is not advisable for the PM to be a SCRUM Master which I can see as making sense as the PM oversees the project whereas the SCRUM Master is more concerned with managing the work packages.

To my mind it would seem that having a PM as SCRUM Master goes against managin by exception, one of the principles of PRINCE2.

The PM should be more concerned with:

establishing the scope of the project, ensuring the business case for
the project remains valid

planning the number of iterations

maintaining the overall project plan including software release dates

acquiring external resources needed by the Scrum team e.g. users for
User Acceptance Testing

managing risks and issues which are escalated by the Scrum team

communicating with the executive including reporting progress

Could any PM's (or SCRUM Masters) experienced in managing agile projects using SCRUM give their experience/opinion on whether the two roles could/should be combined?

答:
I totally agree with @Thomas Owens's answer but I'm adding my own experience.

In typical Scrum project there is no PM. The PM role is divided into all participants of the project - PO, Scrum Master and team. When you scale a Scrum project or when you try to apply Scrum in corporate environment the additional person like a PM can be handy.

Scaling agile is generally hard task and usually demands some plan driven additions to make the scaling successful. PM can be on the top of the whole project and coordinate it with help of teams' Scrum Masters and Product owner.

We even don't need to work on scaling - it is enough if you have to integrate your work with another team which doesn't use agile methodology. In such case a lot of additional coordination is needed. You usually cannot put the burden of coordinating non agile team on Scrum Master or Product Owner but you can use traditional PM coordinating both teams and cooperating with Scrum Master and Product Owner.

The whole separate story is corporate / enterprise environment and bureaucracy. If the company itself didn't move to agile mindset you will simply need PM and he will most probably be "adapter" between your agile world and company's bureaucracy.