问:
How to evaluate the performance of a Data Access Layer b/w two ORM's?
I am currently working on a project where I am going to replace the  Data Access Layer from a custom ORM to Entity Framework.(The product is almost complete and mostly any changes that will follow after its completion would be change requests or bug fixes).

When comparing the two ORM's what performance metrics should I
consider and why?

答:
The absolute most important metric would be the number of database queries executed. If the ORM's translation of the logical code result in a different number of queries, this will have an effect that will dwarf any other difference. You should be especially on the lookout for "n+1"-pattern where the ORM will perform an individual query for each item in a collection when you traverse sub-objects. At least in EF you often have the choice between eager and lazy (n+1) loading of sub-objects, so be sure you know how to use the ORM optimally before dismissing one or the other.

Second, you should look at the amount of data returned from the database. There could be a difference if one ORM performs some filtering on the client side and another does in the sql. Some ORMS are smarter than others in how they translate filters to sql. Obviously it is preferable to filter as much as possible on the database side.

If the ORM's on the other hand generates equivalent sql (which is not unlikely), the performance difference will likely be small, maybe even negligible, and you should base your choice on other factors like maintainability and developer familiarity.


问:
Non-zero exit status for clean exit
Is it acceptable to return a non-zero exit code if the program in question ran properly? For example, say I have a simple program that (only) does the following:

Program takes N arguments. It returns an exit code of min(N, 255). Note that any N is valid for the program.

A more realistic program might return different codes for successfully ran programs that signify different things. Should these programs instead write this information to a stream instead, such as to stdout?

答:
A good example: man sa-update (spamassassin)

EXIT CODES

An exit code of 0 means an update was available, and was downloaded and installed successfully if --checkonly was not specified.

An exit code of 1 means no fresh updates were available.

An exit code of 2 means ...

In this case, exit 1 is simply an informative code. However, if I would have written the code, I would not have chosen 1 since that usually mains failure.

ContentLicense: CC BY-SA 3.0

Title: Non-zero exit status for clean exit


问:
Does path coverage guarantee finding all bugs?
If every path through a program is tested, does that guarantee finding all bugs?

If not, why not? How could you go through every possible combination of program flow and not find the problem if one exists?

I hesitate to suggest that "all bugs" can be found, but maybe that is because path coverage isn't practical (as it is combinatorial) so it isn't ever experienced?

Note: this article gives a quick summary of coverage types as I think about them.

答:
Part of the issue is that 100% coverage only guarantees that the code will function correctly after a single execution. Some bugs like memory leaks may not be apparent or cause issue after a single execution, but over time will cause problems for the application.

For example, say you have an application which connects to a database. Perhaps in one method the programmer forgets to close the connection to the database when they are done with their query. You could run several tests over this method and find no errors with it's functionality, but your database server may run into a scenario where it is out of available connections because this particular method did not close the connection when it was done and the open connections must now timeout.


问:
Why are people making tables with divs?
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

答:
The question is if the data is semantically a table (i.e. a set of data or units of information logically organized in two dimensions) or you just use the grid for visual layout, e.g. because you want a sidebar to expand or something like that.

If your information is semantically a table, you use a
-tag. If you just want a grid for layout purposes, you use some other appropriate html elements and use display:table in the style sheet.

When is data semantically a table? When the data is logically organized along two axes. If it makes sense with headers for the rows or columns, then you might have a semantic table. An example of something which is not semantically a table is presenting a text in columns like in a newspaper. This is not semantically a table, since you would still read it linearly, and no meaning would be lost if the presentation was removed.

OK, why not use
 for everything rather than only for something that is semantically a table? Visually it is obviously the same (since the table element just have display:element in the default style sheet).

The difference is that the semantic information can help alternative user agents. For example a screen reader might allow you to navigate in two dimensions in the table, and read the headers for a cell for both axes if you forget where you are. This would just be confusing if the table was not semantically a table but just used for visual layout.

The
 versus display:table discussion is just a case of the more general principle of using semantic markup.
See for example: Why would one bother marking up properly and semantically? or Why is semantic markup given more weight for search engines?

In some places you might actually be legally required to use semantic markup for accessibility reasons, and in any case there is no reason to purposefully make your page less accessible.

Even if you don't care for disabled users, having presentation separate from content gives you benefits. E.g. your three column layout could be presented in a single columns on a mobile using an alternative stylesheet.

Title: Why are people making tables with divs?

Body:
The question is if the data is semantically a table (i.e. a set of data or units of information logically organized in two dimensions) or you just use the grid for visual layout, e.g. because you want a sidebar to expand or something like that.

If your information is semantically a table, you use a <table>-tag. If you just want a grid for layout purposes, you use some other appropriate html elements and use display:table in the style sheet.

When is data semantically a table? When the data is logically organized along two axes. If it makes sense with headers for the rows or columns, then you might have a semantic table. An example of something which is not semantically a table is presenting a text in columns like in a newspaper. This is not semantically a table, since you would still read it linearly, and no meaning would be lost if the presentation was removed.

OK, why not use <table> for everything rather than only for something that is semantically a table? Visually it is obviously the same (since the table element just have display:element in the default style sheet).

The difference is that the semantic information can help alternative user agents. For example a screen reader might allow you to navigate in two dimensions in the table, and read the headers for a cell for both axes if you forget where you are. This would just be confusing if the table was not semantically a table but just used for visual layout.

The <table> versus display:table discussion is just a case of the more general principle of using semantic markup.
See for example: Why would one bother marking up properly and semantically? or Why is semantic markup given more weight for search engines?

In some places you might actually be legally required to use semantic markup for accessibility reasons, and in any case there is no reason to purposefully make your page less accessible.

Even if you don't care for disabled users, having presentation separate from content gives you benefits. E.g. your three column layout could be presented in a single columns on a mobile using an alternative stylesheet.


答: Path coverage cannot tell you whether all the required features have been implemented. Leaving out a feature is a bug, but path coverage will not detect it.</p>

Title: Does path coverage guarantee finding all bugs?

Body:
If every path through a program is tested, does that guarantee finding all bugs?

If not, why not? How could you go through every possible combination of program flow and not find the problem if one exists?

I hesitate to suggest that "all bugs" can be found, but maybe that is because path coverage isn't practical (as it is combinatorial) so it isn't ever experienced?

Note: this article gives a quick summary of coverage types as I think about them.


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
I've found online reading to be quite useful for reading things sequentially.  You can get the book you need NOW, and you can search in it.

For references, I need a paper copy in my bookshelf, but I only need it for a fraction of the books I've read online.

ContentLicense: CC BY-SA 2.5

Title: eBook editions of programming books


问:
Why not XHTML5?
So, HTML5 is the Big Step Forward, I'm told.  The last step forward we took that I'm aware of was the introduction of XHTML.  The advantages were obvious: simplicity, strictness, the ability to use standard XML parsers and generators to work with web pages, and so on.

How strange and frustrating, then, that HTML5 rolls all that back: once again we're working with a non-standard syntax; once again, we have to deal with historical baggage and parsing complexity; once again we can't use our standard XML libraries, parsers, generators, or transformers; and all the advantages introduced by XML (extensibility, namespaces, standardization, and so on), that the W3C spent a decade pushing for good reasons, are lost.

Fine, we have XHTML5, but it seems like it has not gained popularity like the HTML5 encoding has.  See this SO question, for example.  Even the HTML5 specification says that HTML5, not XHTML5, "is the format suggested for most authors."

Do I have my facts wrong?  Otherwise, why am I the only one that feels this way?  Why are people choosing HTML5 over XHTML5?

答:
You will never get the benefits of a simpler parser or standard XML tools on the client side anyway.

There are billions of pages on the web in HTML, some of them are written by people long dead, so they are never going to be updated to XML. So if you want to create a generally useful user agent you have to be able to parse old fashioned HTML anyway. Arguably XHTML only introduces additional complexity since it requires a new mode of parsing in addition to the HTML parsing you already have to support.

On the server side you can still take advantage of XML tools by eg. generating XHTML using XSLT. But if you are not specifically using a XML toolchain, there is no benefit in using XML syntax rather than just HTML.

(You are not correct that HTML is "non standard" syntax. The syntax of HTML is specified in painstaking detail in the HTML5 spec, so it is just as much a standard as XML syntax.)

Title: Why not XHTML5?


问:
NoSQL within SQL Server
This question is not about the difference between SQL and NoSQL. I am looking for some rationale for something that really does not make sense to me at the moment (maybe because of my lack of understanding or appreciation).

We have started a new project from scratch using MVC5, Entity framework 6 code first and SQL Server 2008. When the architect reviewed the database schema it was stated that all foreign keys and other such constraints should be removed as this is “business logic” and should be applied within the business layer of the application code.

My opinion is that foreign keys form part of data/referential integrity and do not really mimic business logic. I see business logic as more the process and validation which controls what/when/how/why references are applied. I can kind of understand that unique constraints are arguably business processes, but for me this just complements the logic and forms part of the integrity.

A second argument is the aim is to adopt a NoSQL approach to the data. I found this really unusual and unorthodox: considering the use of SQL-Server 2008, the need for reporting, the data not scaling to terabytes and the lack of consideration towards technologies such as Mongo, Raven, etc.

Has anyone came across such a scenario before? Why would anyone adopt a NoSQL approach in an SQL Server designed for referential data and not want foreign keys?

答:
I've yet to have a reason to create a foreign key

-Joel Spolsky

Blanket statements aside, it is worth acknowledging there are legitimate and strong reasons to chose to not use uniqueness or foreign keys constraints. Most go something like this:

Performance. Doing integrity checks with atomic transactions is not free. And frequently, the database is most difficult part of your architecture to scale. Perhaps you already do the checks in your application logic, and would rather not incure a second performance hit.

Lack of need. Perhaps your data is dirty, and you are okay with that. This depends very much on what you are doing.

See also What's wrong with foreign keys?

But those don't match the reasons in your question.

This is business logic and should be applied within the business layer.

This reason is a bit odd. Uniqueness and other integrity constraints are very much the domain of an ACID database. Your application code cannot approach the atomicity and integrity guarantees of SQLServer. If you need strong data integrity, you'd be foolish to ignore the database.

A second argument is that they want to adopt the NoSQL approach to their data storage and so do not want such restrictions in place.

The second reason isn't really a reason; it's a conclusion. Though it is true that constraints are a trade-off between correctness and performance, and NoSQL databases bias towards the latter.

Perhaps your system architect has these legitimate reasons in mind, and you misheard. Or maybe he's a blathering idiot.

In any case, there are valid (though not universal) reasons to refrain from using uniqueness and foreign key constraints.

P.S. If you conclude that you don't want foreign keys, it's still okay to use a relational database. As a generalization, relational databases are more mature than their NoSQL counterparts. As a single node, they can even be faster, and a NoSQL abstraction can be built on top of them.

Title: NoSQL within SQL Server


问:
What practical steps do you take to ensure you are thorough?
Bit of Context

I'm not sure if this is fitting to the programmers.stackexchange area, but I'm not going to post it in SO. Any problem with ambiguity and I'll happily remove it.

If I had to talk openly about my skills and how I sit in a company, I'd say I'm mid-level and about a solid year or two's worth of work away from shooting for a senior position. I'm a C# developer with a strong(ish) background and have a pro-active attitude but my downfall, however, seems to be how thorough I am, and it needs improving fast.

I've had code reviews lately, and it's brought it to my attention that I leave careless holes in what I code before I'm happy to push it over to peers for review. The kind of holes that are embarrassing to hear about, it's not stuff that's outside of the realm of what I already know and are very aware shouldn't be there. For example, I had multiple controller actions today with missing [HttpPost] attributes - something I'm well aware should be there, but were not.

Question:

What approach do you take (or what do you incorporate into your approach) to coding tasks that help avoid carelessness and ensure you're doing a thorough job?

I'm looking for some tangible measures I can put in place today to help. Do you write out what you want to do in plain text or pseudo code first? Do you break your tasks down into much more smaller tasks first with your own set of low-level requirements? Do you write myself a mini tech-spec first? Do you use unit tests to a level that's granular enough to help defend against silly mistakes?

I'm not convinced this problem is entirely down to mind set, I'm convinced my approach is off somehow, and I can't see me tackling the next level without cracking this first.

答:
Lots of good answers already, so I won't duplicate them. However, one other process I've found useful is performing a self review of your code before yours send it out.

This is a really simple thing to do and it will make you team mates lives reviewing your code a lot easier. All you do is look at your diff before you send it out and do a quick code review yourself. If you send notes to your colleagues explaining the change this is the time to write those as well. I find that going through the review with a view of making it accessible to my team mates helps me spot things that could be clearer, or cleanup steps I've missed. Also it saves your teammates time in the review as they find less stuff to fix.


问:
How to infer the result of a query?
To understand what a query does, I have always thought the following is the procedure on evaluating a query:

Form the table as specified in the FROM clause.

Pick the rows from that table as specified in the WHERE clause.

Show the columns of the resulting rows, as specified in the SELECT clause.

But the problem is; all around, I see that SQL is a declarative language. That is, there is no guarantee how a particular query will be executed. Given that, my question is:

Is reasoning about the result of a query in the way I do wrong? If so, how am I supposed to reason about the result of a query? In other words, if I am not able to reason in a step by step basis, how am I supposed to predict what will the result of a particular query be?

Thing is, although this is not a big problem in trivial queries, as queries gets more complex, such as by incorporating various correlated subqueries, I can't see how am I supposed to understand what a query does, without thinking about the query in a step-by-step execution. So, I would like to learn how to reason about SQL queries.

答:
You are indeed able to precisely determine what a query will return by using logical reasoning as you described.

What SQL does not guarantee is how the engine will find this result. It will give the same result as if it used the logical steps you describe, but how it actually finds the result depends on a number of factors and implementation details.

For example, when you say "Pick the rows from that table..." the engine might actually not need to look a the table at all, if there is an index which includes all the columns you as for. Of course this means the engine have to look at the columns first to determine what tables or indexes is should use. So the engine will not actually follow the steps you describe, but the result will be the same.

If you take correlated subqueries, the result will look as if the correlated subquery will be executed once per row in the main query, but in reality the query optimizer might transform the query into a join which is much faster to execute.

Title: How to infer the result of a query?


答:
Actually, I would say that the use of class names like "table" in your example demonstrates how people don't actually understand what they're doing when trying for semantic markup. They get marks for trying to show that the content is not tabular data, but they lose marks for bad class names.

```<code><div class="table">
  <div class="row">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
</div>
</code>```

All that this developer has done is replicate the original
 markup with CSS class names. This means as soon as this layout is not a table, the class names are at odds.

What this developer should have done is consider what information is in the table - is it a thumbnail gallery? Well, then:

```<code><div class="thumbnail-gallery">
  <div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
  </div>
</div>
</code>```

Now I can create some adaptive CSS:

```<code>@media screen {
  .thumbnail-gallery {
    display: table;
    border-collapse: collapse;
    width: 100%;
  }

  .thumbnail-gallery > div {
    display: table-row;
  }

  .thumbnail-gallery .thumbnail {
    display: table-cell;
    border: 1px solid #333333;
  }
}

@media screen and (max-width: 640px) {
  /** reset all thumbnail gallery elements to display as block and fill screen **/
  .thumbnail-gallery,
  .thumbnail-gallery > div,
  .thumbnail-gallery .thumbnail {
    display: block;
    width: 100%;
  }
}
</code>```

Why divs and not tables

A table contains tabular data - presentation of a table is inextricably linked to the structure of a table. Tabular data will always need to be in tabular form no matter where you put that content or on what screen/device you want it to display.

A thumbnail gallery (or many other things, like a registration form, a menu, and more) is not tabular data. It may be presented like a table in some design layouts, but in other cases, like narrow phone screens, you want it using more traditional block layouts. Or perhaps you want to display thumbnails in a sidebar instead of in the main content area.

Your choice is now to output different markup for the wide screen content (tables) and sidebar or narrow screen content (divs) - which means your server side scripts will have to be aware of where the content is going if you're building this programmatically - or you have your server side script output the same markup (because it shouldn't care where you're putting this) and use different CSS rules for the different situations.

So, then you have a choice of always outputting tables, and then overriding the natural table display rules with block (which really should grind some gears in any developers head), or going with well labelled divs which allow more flexible approaches to styling.

And best practices for several years now has been to avoid tables when not needing to present tabular data.

Title: Why are people making tables with divs?

Body:
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

Body:
Actually, I would say that the use of class names like "table" in your example demonstrates how people don't actually understand what they're doing when trying for semantic markup. They get marks for trying to show that the content is not tabular data, but they lose marks for bad class names.

<div class="table">
  <div class="row">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>
</div>

All that this developer has done is replicate the original <table> markup with CSS class names. This means as soon as this layout is not a table, the class names are at odds.

What this developer should have done is consider what information is in the table - is it a thumbnail gallery? Well, then:

<div class="thumbnail-gallery">
  <div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
    <div class="thumbnail">
      <img src="" />
      <p>Some text</p>
    </div>
  </div>
</div>

Now I can create some adaptive CSS:

@media screen {
  .thumbnail-gallery {
    display: table;
    border-collapse: collapse;
    width: 100%;
  }

  .thumbnail-gallery > div {
    display: table-row;
  }

  .thumbnail-gallery .thumbnail {
    display: table-cell;
    border: 1px solid #333333;
  }
}

@media screen and (max-width: 640px) {
  /** reset all thumbnail gallery elements to display as block and fill screen **/
  .thumbnail-gallery,
  .thumbnail-gallery > div,
  .thumbnail-gallery .thumbnail {
    display: block;
    width: 100%;
  }
}

Why divs and not tables

A table contains tabular data - presentation of a table is inextricably linked to the structure of a table. Tabular data will always need to be in tabular form no matter where you put that content or on what screen/device you want it to display.

A thumbnail gallery (or many other things, like a registration form, a menu, and more) is not tabular data. It may be presented like a table in some design layouts, but in other cases, like narrow phone screens, you want it using more traditional block layouts. Or perhaps you want to display thumbnails in a sidebar instead of in the main content area.

Your choice is now to output different markup for the wide screen content (tables) and sidebar or narrow screen content (divs) - which means your server side scripts will have to be aware of where the content is going if you're building this programmatically - or you have your server side script output the same markup (because it shouldn't care where you're putting this) and use different CSS rules for the different situations.

So, then you have a choice of always outputting tables, and then overriding the natural table display rules with block (which really should grind some gears in any developers head), or going with well labelled divs which allow more flexible approaches to styling.

And best practices for several years now has been to avoid tables when not needing to present tabular data.


问:
'Tuple' vs 'List' operations in python
Only two operations are allowed on tuple, as shown below.

Operations like insert / delete at an index is not allowed. I learnt that tuple is an immutable data model.

list allows insert and delete operations. I learnt that list is the mutable data model.

My question:

Is it mutability factor, that does not allow tuple to perform insert and delete operations?

答:
Yes. The insert and delete operations change an existing object, rather than creating a new one with a different set of elements. Any type that allows those operations is clearly mutable.

The equivalent of an insert/delete operation for an immutable type like a tuple would be constructing a new tuple that's only one element different from the original. For instance, >>> tup[0:n] + (x,) + tup[n:] is sort of like inserting x after element n, and >>> tup[0:n-1] + tup[n+1:] is sort of like deleting element n.

Why do we care about immutable types? Because they're less error prone. Consider:

```<code>>>> x = 3
// many lines of code that don't mention x
>>> x
=> 3
</code>```

It seems obvious that if you don't assign a new value to x, the value of x should not have changed. With immutable types like integers and tuples, this is guaranteed by the language. You can safely make the assumption that no direct changes to x means x has the same value it did when you left it.

With mutable types like tuples, you can't ever make that assumption.

```<code>>>> x = [1, 2, 3]
>>> y = x
>>> x
=> [1, 2, 3]
>>> y.insert(1, 999) // we're not using x here
>>> x
=> [1, 999, 2, 3]    // but somehow x changed anyway
</code>```

This is just a toy example. In very large programs where a mutable variable can potentially be accessed from hundreds or thousands of different places in any order, it's impossible to keep track of who might be modifying it or expecting who else to modify it at certain times.

This overlaps heavily with the more well-known argument that global variables are evil. Immutable global variables are much less evil.

Title: 'Tuple' vs 'List' operations in python

Body:
Yes. The insert and delete operations change an existing object, rather than creating a new one with a different set of elements. Any type that allows those operations is clearly mutable.

The equivalent of an insert/delete operation for an immutable type like a tuple would be constructing a new tuple that's only one element different from the original. For instance, >>> tup[0:n] + (x,) + tup[n:] is sort of like inserting x after element n, and >>> tup[0:n-1] + tup[n+1:] is sort of like deleting element n.

Why do we care about immutable types? Because they're less error prone. Consider:

>>> x = 3
// many lines of code that don't mention x
>>> x
=> 3

It seems obvious that if you don't assign a new value to x, the value of x should not have changed. With immutable types like integers and tuples, this is guaranteed by the language. You can safely make the assumption that no direct changes to x means x has the same value it did when you left it.

With mutable types like tuples, you can't ever make that assumption.

>>> x = [1, 2, 3]
>>> y = x
>>> x
=> [1, 2, 3]
>>> y.insert(1, 999) // we're not using x here
>>> x
=> [1, 999, 2, 3]    // but somehow x changed anyway

This is just a toy example. In very large programs where a mutable variable can potentially be accessed from hundreds or thousands of different places in any order, it's impossible to keep track of who might be modifying it or expecting who else to modify it at certain times.

This overlaps heavily with the more well-known argument that global variables are evil. Immutable global variables are much less evil.


答:
From a theoretical standpoint, yes, the immutability of tuples is the reason for their lack of insert and delete.

More accurately, it is the lack of the implementation of methods for insert and delete that makes tuples immutable since Python uses runtime, duck typing for type checking. You call a method on an object and the object will either reply with the results of that method or it will return an AttributeError.

Title: 'Tuple' vs 'List' operations in python

Body:
Only two operations are allowed on tuple, as shown below.

Operations like insert / delete at an index is not allowed. I learnt that tuple is an immutable data model.

list allows insert and delete operations. I learnt that list is the mutable data model.

My question:

Is it mutability factor, that does not allow tuple to perform insert and delete operations?


问:
Best use of the React frontend framework
I've been using rails' erb template for my views, but I've recently been trying to incorporate React as my front end framework. I'm a little lost on how front end frameworks are supposed to be used.

e.g. Using React to render a static button

```<code>var AddProspects = React.createClass({
  displayName : 'AddProspects',
  render: function() {
    return (
        <button type="button" className="btn btn-info pull-right btn-block" data-toggle="modal" data-target="#uploadModal">
            <i className="fa fa-plus"></i> Upload Prospects
        </button>
    );
  }
});

React.render(<AddProspects />, document.getElementById("#add-prospects"));
</code>```

e.g. Using normal html

```<code><button type="button" class="btn btn-info pull-right btn-block" data-toggle="modal" data-target="#uploadModal">
  <i className="fa fa-plus"></i> Upload Prospects
</button>
</code>```

Using React in this example seems to be a overkill.

Should I be using React for the whole view? Should React be rendering everything from static html to dynamic data from the server side? Or is it better to use it just for elements that interact with the server and leave static stuff to plain html?

答:
React is focused on using plain html.

That is why you can just type HTML tags inside your react code. The idea is to keep it simple.

Simple answer is: Yes, you should write a lot of plain HTML. When you need to program some piece to use it inside React, then define it on ReactJS. I believe a greate rule of thumb is: When in doubt, think what will be messier (Harder to maintain the code later), and do things the other way. :D


问:
How can a statically typed language support duck typing?
I understand what dynamic and static type systems are, and what duck typing is. But I don't understand how you can have a static language that supports duck typing. To my understanding only a dynamically typed language can support duck typing.

This answer from StackOverflow explains that "Duck typing is something that is completely orthogonal to static, dynamic, weak, or strong typing." It gives an example from C++ for duck typing in a statically typed language, but I'm not a C++ programmer and I don't understand it.

I'd like an explanation of how it's possible for a static language to support duck typing.

答:
It doesn't have to be. You can implement 95%ish of duck typing in a static language without that much work. The last 5% you need dependent typing for and it's much more complicated, but that's still a statically typed system. Specifically, the remaining 5% is for conditionally using methods depending on other values, and so having code that still works on data that does not support all of the methods you code conditionally calls.

Here's a chunk of Haskell that I was tinkering with and it implements something very much like static duck typing:

```<code>{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances,
UndecidableInstances, IncoherentInstances, FlexibleContexts #-}

data Addon a b = Addon a b deriving Show

class Plugin a b where
    first :: b -> a
    set   :: a -> b -> b

instance Plugin a a where
    first = id
    set   = const

instance Plugin a (Addon a b) where
    first (Addon a _) = a
    set x (Addon a b) = Addon x b

instance (Plugin a b) => Plugin a (Addon c b)where
    first (Addon _ b) = first b
    set x (Addon a b) = Addon a $ set x b

class Runnable e b c where
    run :: e -> b -> c

instance Plugin a b => Runnable (a -> c) b c where
    run f p = f (first p)

instance (Plugin d b, Runnable e b c) => Runnable (d -> e) b c where
    run f p = run (f $ first p) p

-- The constructor function should NOT be polymorphic *at all*
apply constructor f x = set (constructor $ run f x) x
</code>```

The Plugin typeclass exists to express containment of types within other types. A type which is an instance of Plugin a b means that it is a type b for which first b can be a value of type a. The two instances given are all that is needed to derive all relevant cases and no further instance declarations are needed.

The Runnable typeclass allows us to chain Plugin instances together and so call a curried multi-argument function on a single datatype so long as it contains a valid component type for each curried argument of the function. Again, no further instance declarations are needed for usage.

The apply function allows us to take a composite type, apply a function to it, and store the result inside that composite type (so long as it already contains a value of the type we wish to store)

Usage would look like so:

```<code>data Increment = Inc Integer
data Counter   = Count Integer

counter1 = union (Inc 2) (Count 3)
counter2 = union (Inc 1) (Count 0)

increment (Inc i) (Count c) = i + c
</code>```

And indeed, this compiles, and we can run it and observe the output:

```<code>*Main> apply Count increment counter1
Addon (Inc 2) (Count 5)
*Main> apply Count increment counter2
Addon (Inc 1) (Count 1)
</code>```

Granted, we had to turn on some rather ugly type extensions, but those extensions are not required to use the library, only to write it. The constructor argument to apply cannot be polymorphic because that would overload the type inference system and it would be unable to make the necessary intermediate type derivations. I was trying to get around that, but I have not made any progress in that direction.

Body:
It doesn't have to be. You can implement 95%ish of duck typing in a static language without that much work. The last 5% you need dependent typing for and it's much more complicated, but that's still a statically typed system. Specifically, the remaining 5% is for conditionally using methods depending on other values, and so having code that still works on data that does not support all of the methods you code conditionally calls.

Here's a chunk of Haskell that I was tinkering with and it implements something very much like static duck typing:

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances,
UndecidableInstances, IncoherentInstances, FlexibleContexts #-}

data Addon a b = Addon a b deriving Show

class Plugin a b where
    first :: b -> a
    set   :: a -> b -> b

instance Plugin a a where
    first = id
    set   = const

instance Plugin a (Addon a b) where
    first (Addon a _) = a
    set x (Addon a b) = Addon x b

instance (Plugin a b) => Plugin a (Addon c b)where
    first (Addon _ b) = first b
    set x (Addon a b) = Addon a $ set x b

class Runnable e b c where
    run :: e -> b -> c

instance Plugin a b => Runnable (a -> c) b c where
    run f p = f (first p)

instance (Plugin d b, Runnable e b c) => Runnable (d -> e) b c where
    run f p = run (f $ first p) p

-- The constructor function should NOT be polymorphic *at all*
apply constructor f x = set (constructor $ run f x) x

The Plugin typeclass exists to express containment of types within other types. A type which is an instance of Plugin a b means that it is a type b for which first b can be a value of type a. The two instances given are all that is needed to derive all relevant cases and no further instance declarations are needed.

The Runnable typeclass allows us to chain Plugin instances together and so call a curried multi-argument function on a single datatype so long as it contains a valid component type for each curried argument of the function. Again, no further instance declarations are needed for usage.

The apply function allows us to take a composite type, apply a function to it, and store the result inside that composite type (so long as it already contains a value of the type we wish to store)

Usage would look like so:

data Increment = Inc Integer
data Counter   = Count Integer

counter1 = union (Inc 2) (Count 3)
counter2 = union (Inc 1) (Count 0)

increment (Inc i) (Count c) = i + c

And indeed, this compiles, and we can run it and observe the output:

*Main> apply Count increment counter1
Addon (Inc 2) (Count 5)
*Main> apply Count increment counter2
Addon (Inc 1) (Count 1)

Granted, we had to turn on some rather ugly type extensions, but those extensions are not required to use the library, only to write it. The constructor argument to apply cannot be polymorphic because that would overload the type inference system and it would be unable to make the necessary intermediate type derivations. I was trying to get around that, but I have not made any progress in that direction.


问:
Planning complex Mongo (And possibly other NoSQL) Databases
There is no "right way" to do anything, but there are "better" and "worse" ways, as well as true and tested ways.

I'm studying Mongo and considering it for a project. It's gonna start small but possibly grow a lot.

Now, I understand there are different ways to organize information in MongoDB. Since there are no joins, I either insert ids (Or arrays) and do multiple queries to get a related item (I.e. person for a company, company Id on people object or array of people on company table), or I insert objects directly inside... (I.e., people as objects in an array inside the company, as opposed to being "decoupled").

Now, my issue is: what if I need to change how I load this info?

A good example, taking the users idea, is if I wanna get all people (Of all companies) inactive for the last month. Now, would I need to look separately into one company at a time to query this information? Should I keep them separate and use ids as references in this case...?

What are the tradeoffs, the performance impacts, and which approach is considered "more appropriate" by the community?

答:
As noted by John F. Miller on another question at SO (https://stackoverflow.com/a/5373969/1793074), MongoDB is great at nesting data, but not so grat to search this nested data.

Another great resource on this matter comes from the same answer:
http://seanhess.github.io/2012/02/01/mongodb_relational.html

Basically, you relinquish control when you work with "documents inside documents". A lot of controle.

With that said, the suggested approach is to only insert a document inside another if the "inside-document" is absolutelly dependant on the outside one. Then, and only then, you can "skip collections".

You can, though, insert objects that reference other collections, using denormalization techniques to have performance gains.

What to choose is up to each project, but for data that has to be queried and used in different situations, the best is to have separate collections, and reference by id or dennormalizing for faster access.


问:
As a lone developer, how can I be sure I am learning and doing decent work?
Background: I work in a small (less than 75) person engineering/manufacturing company. I was hired as a developer to work with a single teammate, our purpose being to migrate the company to the modern digital age. My teammate however is not a developer, but instead an industrial engineer, who primarily works on broad ideas, planning, and other non-code related areas. I do all the development.

Problem: I enjoy my work, and it's (shockingly) low stress, probably due to the fact that pretty much no one understands what I do. This includes my boss, he hired me only knowing that he needed someone who can "code". The problem with this is that I am forced to solve every task myself, without any input from colleagues/seniors. I am very good at what I do, but also quite young (haven't even started college yet), and so I would have seriously benefited from having seniors to teach and correct me. Unfortunately this isn't possible at the current time, so I'm stuck doing everything my way and hoping it works out.

This works I suppose, except I have no way to know if I am doing things in a terrible fashion that will eventually cost me months of rework time. Am I doing things efficiently? And although I haven't run into this yet, what if I really just can't figure out a problem that blocks our project? I can't hand it off! And what about when I leave? What if the next developer grows to curse my very being because of what lays before his eyes? :)

These questions worry me quite frequently, and it brings me to my question:

As a lone developer, what can/should I do to make sure I am learning, and producing efficient, maintainable, and proper (near bug free) code. How can I do things like:

review my own code

review my own designs

etc.

EDIT:

My question is similar but not a duplicate of Can a lone programmer become a mid or senior level programmer without a mentor?, that question is about "ranking up" as an individual programmer, I am asking how I can make sure I am learning and doing things properly without any other technical oversight.

答:
How do I know if I'm doing things right?

it's never done, perfect, unable to be improved on.  but it's still good to measure your work (which is code) according to some metric or metrics of performance.  i sent you a powerpoint of something i presented in 2008.

there are some obvious metrics that i thought are salient:

Is this stuff you wanna do?

Make cool product

Uses your Intellectual Property

Niche market (e.g. audio)

Make money

Expect to have a future:

a) Long term vs. short term interests

b) Leverage old into new

Does your code:

Performs a cool function (that's the main idea)

Cost:

required hardware

execution time (speed)

space (tight loops)

non-recurring (NRE)

Future value:

maintainability,

reusability,

portability

Decide what's important, see how well your code scores with the goals you have for it.

OwnerDisplayName: Josiah


答:
If every path through a program is tested, does that guarantee finding all bugs?

As already said, the answer is NO.

If not, why not?

Besides what is being said, there are bugs appearing at different levels, which can't be tested with unit tests. Just to mention few :

bugs caught with integration tests (unit tests shouldn't use real resources after all)

bugs in requirements

bugs in design and architecture


问:
How to make sure clean code well implemented?
I'm a project manager in a small team of developers (consisting 3 team leaders and 10 programmers)

We're currently trying to enforce clean code for our team , we're having small frequent seminars discussing uncle bob's clean code book.

Long story short, we are trying to make sure that clean code are well implemented in our team. to do that we're asking our team leaders to review their team's committed code daily and take note whenever a piece of code aren't clean enough. By using this method, all the team leaders are completely overwhelmed by the amount of code that they have to review everyday and cannot review the codes in detailed manner.

is there any better method to review codes to make sure they are clean? we want to make clean code to become habit as soon as possible.

Thank you

答:
You let the team review each others code. Use your team leaders to spot check at random. This means the team is part of the solution, becomes more involved in the whole process, and spreads the task so its achievable.

Invest in a code review tool such as reviewboard or redmine's plugin to help make reviewing easier and quicker too.


问:
Is there any better approach to shortest path finding within a (vehicular) traffic network?
Dear fellow programmers,

We're developing software which simulates vehicular traffic.
Part of the process called "assignment" is concerned with assigning vehicles to their routes and has to use some kind of shortest-path-finding algorithm.

Traditionally, people do this with Dijkstra's, and certain scientific literature seems to indicate that A* and other alternatives don't give any significant improvement, perhaps due to the nature of the graph.

Hence, we're using Dijkstra's as well. A small problem arose in that, if you treat traffic links (spans of roads between intersections) as edges and intersections as nodes, you can't get a classic uni-directional graph:
when approaching an intersection, where you can turn frequently depends on where you're coming from, whereas in a traditional graph you can take any edge from a node.

We resolved this problem quite easily by representing a link-intersection pair (call it "lath") as a node. Since you'd need to traverse a link to get to any subsequent "lath", or point of choice, an edge would then be defined as this traversal, and you get a typical graph.

The results then are stored in a simple table, N x N, where N is the number of "laths."

Here's the (unavoidable?) drawback. If a typical network for our simulation can have, say, 2000 intersections, it will have somewhere around 6000 links, i.e. N = 3V. Obviously, if counted in terms of intersections (V), we're now up to O(log(3V)*(3V + E)).

You might argue that 3 (or 9) is a constant factor, but from the practical standpoint, it does slow things down quite a bit, and increases storage space to 3V x 3V.

Does anyone have any idea how we can restructure this to improve performance?
Not necessarily any alternative algorithm, perhaps reshape the data structures to fit a graph in some other way?

答:
You have large graph and you made it even larger. Martinc C. Martin advised using lathes only when needed, so i will not go into this.

One of things that could help you, is tranform your graph into smaller graphs.

First simplification that helped me a lot (I worked with road networks of europian states) was "removing" nodes with digree 1 and 2 recursively. This way you have no dead end roads, and T intersections (originally degree 3) becomes degree 2 and that is not interesting, if you are not pathing to that node or node in that removed cull de sac.

After that, you can try to divide your graph into parts that have large ammount of internal nodes and edges, but have minimal connection with other parts. To find them, I used minimal cut where sink and source were as far from each other (in edges) from each other and edges near them had huge capacity and edges somewhere in between had small.


答: Many (but not all) coding style / safety issues can be caught with tools. Also, tools can be configured to signal a certain subset of infringements. You and your team members should agree upon two sets: (1) should never occur (2) might occur under certain conditions. All team members should submit code that does not generate warnings by set 1. Team leaders need only verify that no code has been checked in that does not pass level 1. That is a trivial task that could easily be done by 1 person or be automated. The issues that remain, by definition, are interesting cases that warrant review and discussion.</p>

Title: How to make sure clean code well implemented?

Body:
I'm a project manager in a small team of developers (consisting 3 team leaders and 10 programmers)

We're currently trying to enforce clean code for our team , we're having small frequent seminars discussing uncle bob's clean code book.

Long story short, we are trying to make sure that clean code are well implemented in our team. to do that we're asking our team leaders to review their team's committed code daily and take note whenever a piece of code aren't clean enough. By using this method, all the team leaders are completely overwhelmed by the amount of code that they have to review everyday and cannot review the codes in detailed manner.

is there any better method to review codes to make sure they are clean? we want to make clean code to become habit as soon as possible.

Thank you


答:
It's clear from the other answers that 100% code coverage in tests does not mean 100% code correctness, or even that all bugs that could be found by testing, will be found (never mind bugs that no test could catch).

Another way of answering this question is one from practice:

There are, in the real world, and indeed on your own computer, many pieces of software that are developed using a set of tests that give 100% coverage and which yet still have bugs, including bugs that better testing would identify.

An entailed question therefore, is:

What is the point of code coverage tools?

Code coverage tools help to identify areas one has neglected to test. That can be fine (the code is demonstrably correct even without testing) it can be impossible to resolve (for some reason a path cannot be hit), or it can be the location of a great stinking bug either now or following future modifications.

In some ways spell-check is comparable: Something can "pass" spell-check and be misspelled in such a way as to match a word in the dictionary. Or it can "fail" because correct words are not in the dictionary. Or it can pass and be utter nonsense. Spell-check is a tool that helps you identify places you may have missed in your proof-reading, but just as it cannot guarantee complete and correct proof-reading, so code-coverage cannot guarantee complete and correct testing.

And of course the incorrect way to use spell-check is famously to go with every suggestion ewe sea it suggest so the ducking thing becomes worse then if ewe left it a loan.

With code coverage it can be tempting, especially if you've a near-perfect 98%, to fill in cases so that the remaining paths are hit.

That is the equivalent of righting with spell-check sew that it's all words weather or knot it's all the appropriate words. The result is a ducking mess.

However, if you consider what tests the non-covered paths really need, the code-coverage tool will have done its job; not in promising you correctness, but it pointing out some of the work that needed to be done.


答:
The one tip I can give is read open source code.

Understand how leading codebases are structured and what coding styles and frameworks are used. That way you will not learn "into the wrong direction" and stay current with the industry for when you switch.

Title: As a lone developer, how can I be sure I am learning and doing decent work?

Body:
Background: I work in a small (less than 75) person engineering/manufacturing company. I was hired as a developer to work with a single teammate, our purpose being to migrate the company to the modern digital age. My teammate however is not a developer, but instead an industrial engineer, who primarily works on broad ideas, planning, and other non-code related areas. I do all the development.

Problem: I enjoy my work, and it's (shockingly) low stress, probably due to the fact that pretty much no one understands what I do. This includes my boss, he hired me only knowing that he needed someone who can "code". The problem with this is that I am forced to solve every task myself, without any input from colleagues/seniors. I am very good at what I do, but also quite young (haven't even started college yet), and so I would have seriously benefited from having seniors to teach and correct me. Unfortunately this isn't possible at the current time, so I'm stuck doing everything my way and hoping it works out.

This works I suppose, except I have no way to know if I am doing things in a terrible fashion that will eventually cost me months of rework time. Am I doing things efficiently? And although I haven't run into this yet, what if I really just can't figure out a problem that blocks our project? I can't hand it off! And what about when I leave? What if the next developer grows to curse my very being because of what lays before his eyes? :)

These questions worry me quite frequently, and it brings me to my question:

As a lone developer, what can/should I do to make sure I am learning, and producing efficient, maintainable, and proper (near bug free) code. How can I do things like:

review my own code

review my own designs

etc.

EDIT:

My question is similar but not a duplicate of Can a lone programmer become a mid or senior level programmer without a mentor?, that question is about "ranking up" as an individual programmer, I am asking how I can make sure I am learning and doing things properly without any other technical oversight.


问:
Dynamic Code Evaluation in Java - Clever or Sloppy?
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).

答:
XACML is the solution you are really looking for. It is a type of rules engine that is focused on access control only. XACML, a standard defined by OASIS, defines three parts:

an architecture

a policy language (which is really what you want)

a request / response scheme (how you ask for an authorization decision).

The architecture is as follows:

the Policy Decision Point (PDP) is the core part of the architecture. It is the component that evaluates incoming authorization requests against a known set of policies

the Policy Enforcement Point (PEP) is the piece of code that protects your application / API / service. The PEP intercepts the business request, creates a XACML authorization request, sends it off to the PDP, receives a response back, and enforces the decision inside the response.

the Policy Information Point (PIP) is the component that can connect the PDP to external sources of data e.g. an LDAP, a database or a web service. The PIP comes in handy when the PEP sends a request e.g. "Can Alice view doc #12?" and the PDP has a policy that requires the user's age. The PDP will ask the PIP "give me Alice's age" and will then be able to process the policies.

the Policy Administration Point (PAP) is the place where you manage the entire XACML solution (defining attributes, writing policies, and configuring the PDP).

Here's what your first use case looks like:

```<code>/*
 * All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized
 *
 */
 policy departmentOne{
    target clause department == 1
    apply firstApplicable
    /**
     * All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized
     */
    rule allowFooBar1{
        target clause resourceId=="FOOBAR-1" and seniority>=5 and actionId=="VIEW"
        permit
    }
    rule denyOtherAccess{
        deny
    }

 }
</code>```

Your second use case would be:

```<code> /*
  * "All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"
  *
  */
  policy departmentTwo{
    target clause department == 1
    apply firstApplicable
    rule allowFooBar2{
        target clause resourceId=="FOOBAR-1" and seniority>=5 and currentDate>"2016/03/15":date and actionId=="VIEW"
        permit
    }
    rule denyOtherAccess{
        deny
    }
  }
</code>```

You can combine both use cases into a single policy by using references:

```<code>  policyset global{
    apply firstApplicable
    departmentOne
    departmentTwo
  }
</code>```

And you're done!

You can read more on XACML and ALFA from:

the XACML Developer's Blog

the XACML Developer's YouTube channel

Body:
XACML is the solution you are really looking for. It is a type of rules engine that is focused on access control only. XACML, a standard defined by OASIS, defines three parts:

an architecture

a policy language (which is really what you want)

a request / response scheme (how you ask for an authorization decision).

The architecture is as follows:

the Policy Decision Point (PDP) is the core part of the architecture. It is the component that evaluates incoming authorization requests against a known set of policies

the Policy Enforcement Point (PEP) is the piece of code that protects your application / API / service. The PEP intercepts the business request, creates a XACML authorization request, sends it off to the PDP, receives a response back, and enforces the decision inside the response.

the Policy Information Point (PIP) is the component that can connect the PDP to external sources of data e.g. an LDAP, a database or a web service. The PIP comes in handy when the PEP sends a request e.g. "Can Alice view doc #12?" and the PDP has a policy that requires the user's age. The PDP will ask the PIP "give me Alice's age" and will then be able to process the policies.

the Policy Administration Point (PAP) is the place where you manage the entire XACML solution (defining attributes, writing policies, and configuring the PDP).

Here's what your first use case looks like:

/*
 * All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized
 *
 */
 policy departmentOne{
    target clause department == 1
    apply firstApplicable
    /**
     * All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized
     */
    rule allowFooBar1{
        target clause resourceId=="FOOBAR-1" and seniority>=5 and actionId=="VIEW"
        permit
    }
    rule denyOtherAccess{
        deny
    }

 }

Your second use case would be:

 /*
  * "All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"
  *
  */
  policy departmentTwo{
    target clause department == 1
    apply firstApplicable
    rule allowFooBar2{
        target clause resourceId=="FOOBAR-1" and seniority>=5 and currentDate>"2016/03/15":date and actionId=="VIEW"
        permit
    }
    rule denyOtherAccess{
        deny
    }
  }

You can combine both use cases into a single policy by using references:

  policyset global{
    apply firstApplicable
    departmentOne
    departmentTwo
  }

And you're done!

You can read more on XACML and ALFA from:

the XACML Developer's Blog

the XACML Developer's YouTube channel


问:
Should I always call super in Java?
Anti-pattern considerations aside, should I always call super in Java when overriding methods, even when the method is empty?

Take a look at the code below, this is an excerpt from AsyncTask and can be found here. AsyncTasks are often used in Android and the only method we must implement is the abstract doInBackground(). Other methods, such as onPreExecute() and onPostExecute(), are useful to override in some cases. Notice that these two methods are implemented but do not actually do anything, that is they are empty.

I've seen claims that because these are empty we do not have to override them. I still do because I do not know whether they'll change it in a future implementation (and because the editor does it for me). Is there a best practice for this case?

```<code>/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
protected abstract Result doInBackground(Params... params);

/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
protected void onPreExecute() {
}

/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
</code>```

答:
I still do because I do not know whether they'll change it in a future implementation (and because the editor does it for me).

A superclass that does this is a bad superclass. The superclass needs to tell you exactly what its implementation (if any) of the non-final method does, under which circumstances it'll be called by other superclass methods, and what you need to do to correctly override it.

Once it specifies these things, it can't go back on them. Just like you need to maintain backwards compatibility of public methods, superclasses need to maintain backwards compatibility of changes to inheritable methods or all hell breaks loose.

Title: Should I always call super in Java?


答:
I would recommend not only dev testing the code but also QA testing it with a few scenarios before passing it on for actual QA testing.

Yes, dev testing takes a bit of time to complete properly with useful comments and such. However, you should look at this as a long-term investment. You won't see results in a week or even a month but over a course of time (a few months let's say even though it depends per team) you will start noticing that the overall standards of your team and the quality of the product has gone higher. There are a few reasons for this:

1) Code reviewing someone else's code helps you learn more either by critiquing what could be improved or being inspired by an elegant solution.

2) When you know that another developer is going to be looking at your code you are more likely to put more effort into making your code look prettier. You don't want to be known as the guy with the messy code. Need for validation is a powerful force.

3) Doing a quick QA testing before passing it on for actual QA testing for BAs/QA Engineers helps you make sure you are passing a more quality product and therefore there is less time spent on communication (when it fails back, they need to write steps how they reproduced it, devs need to switch context, all this takes more time). QA testing by devs just assures that it not only builds but also runs for and works for at least one scenario. Then during actual QA testing more scenarios could be used to test it more thoroughly.

With all these steps you should be able to create a culture where clean code is utilized for designing and developing any projects that come up.


问:
What is the best way to create DTOs from entities and update entities from DTOs in a layered architecture?
Option 1:

At first I would make a call to my service layer, which served as an API for my core domain, to get a domain object or a list of domain objects and then pass them into the assembler which would construct the DTOs I needed for my view. The problem I have with this approach are cases where the domain object is large and I don't want to load in the whole object just to copy a few fields needed for the DTO (ie showing a list of summaries entities).

Option 2:

The next approach I used was to wire in a repository (for read-only purposes) into my assembler so that I could only query the database for the fields I need in the DTO. I can also use this repository when I get a DTO and need to use it to update and entity. For example, a DTO filled will values I need to update on my entity comes into my assembler, the assembler looks up the entity from a repository and then overlays the information from the DTO on the entity and then returns the entity. The controller then calls the service layer to save the entity that the assembler returned.

Option 3:

I could wire in the repositories directly into the controllers but something about exposing the repository in the controller seems wrong to me because the service layer should be handling transactions and security, but then again, if I put a repository in the assembler I am basically doing the same thing.

Any thoughts are welcome. I just want to understand pros and cons and what has worked well for others.

答:
Personally I would not use any of these options.  I would skip the use of repositories all together, and just use ADO.NET and SQL queries to map data to my DTO's directly in the application layer.  Or if you prefer behind a very thin query facade layer.

We use this method with great success currently.  Querying against multiple domain models doesn't give you any real benefits and will generally give you poor performance.  No real reason to get your domain entities involved at all in my opinion.

OwnerDisplayName: Tyler Day


答:
Clean code for my understanding is to adopt standards which allows you to keep correct naming inside the code, correct function and class sizes, on over all a good usage of OO practices. This takes time and it is hard to get it write the first time you write your code. So you must be able to refactor.

The only way I know you can safely Refactor code, is if you followed strictly Test Driven Development. If you refactor the code often and early, after each interaction the code gets cleaner. This means, after each code review the code gets better (in the case of a pair programming session this theoretical can be achieved on the fly.).

The reviews should point improvements to be done by Refactoring.


问:
Ethicality of online license checks
Our program has a piracy problem, some people buy a personal license and install it on all the computers in a company. We want to check that only a single instance of a serial id is used at the same time (or at most, two or three instances, say on a user's laptop and desktop).

We're thinking about having the program call home with a non traceable identifier and the license so long as the program is running (every 15 minutes or some medium length interval like this) and when we see that too many instances are running with the same serial id (let's say the average user has 3 computers max), the next time one of the instances pings us we'll send him back a response to shut down the program and display the message.

We are aware of the fact that the system can be bypassed, we are OK with that, just don't want legitimate users to use the same serial multiple times.

Are there any ethical issues with having the program call about home twice an hour? Would this have a negative impact on how people perceive our software?

答:
There is no ethical problem with doing this, as long as customers are aware of it before they make the decision to purchase the product.

However; if someone purchased the product before it required internet access, and then the product changes without their consent (e.g. using some sort of "auto-update") then I think it is an ethical problem (a form of "bait and switch" where consumers are tricked into buying something they may not have bought otherwise). This includes any expectation of future upgrades (e.g. if the user bought the product knowing they're entitled to future upgrades but are now unable to take advantage of the future upgrades without being forced into "internet access required").

Title: Ethicality of online license checks


问:
Manager reading version control commits
Our manager is monitoring the Git commits on all of our projects; usually this isn't a problem, and I love the fact that version control provides a log of all work that's happening, especially for later auditing and analysis (in case anything goes wrong).

However, the manager has made a few comments asking what people are working on when he sees a commit that reads "style fixes" or any commit message that does not reference a ticket number in our task management system.

Is there a social or technical solution to this?

Further information: this is a maintenance project, so there's a bunch of "had to do A then B then C and then D and then finally got to implement X" tasks happening.

More information: the particular commit message that raised a flag with the manager was close to "included a better way to X, Y and Z" which is more of a refactoring message rather than a simple stylistic fix.

答:
Is there a social or technical solution to this?

I suppose, but this isn't a problem.

Your manager should know what you guys are doing. They should make sure that you're not doing a bunch of work that provides no value, or why non-ticket work was prioritized. There is no harm in this. In an ideal world, it will provide benefit, because your manager can set expectations with business so that you can get all of that work done without pressure or interruption.

It only becomes a problem if your manager thinks that only ticket work should be done, and precludes technical cleanup work from being tickets. There is always technical debt to clean up. Always things to tweak because you should, even though they provide no clear, immediate business benefit.

OwnerDisplayName: anon

Title: Manager reading version control commits


答:
If the stylistic fix is part of the ticket you are working on and it is related then there is nothing wrong with checking it in separately with the same ticket number you were working on for better identification.

If you are just discovering changes that need to be made and they are not related to the ticket that you are currently working on then I would suggest making tech debt related tickets and put them on your backlog for later rehashing.

During your planning you can then go through the tech debt related tickets and attach them to actual maintenance tickets that you are planning on working on this way making it more relatable.

This will help you eliminate those "out of nowhere" fixes and keep everything encapsulated under the category of specific problems/tickets you are working on.

Title: Manager reading version control commits

Body:
Our manager is monitoring the Git commits on all of our projects; usually this isn't a problem, and I love the fact that version control provides a log of all work that's happening, especially for later auditing and analysis (in case anything goes wrong).

However, the manager has made a few comments asking what people are working on when he sees a commit that reads "style fixes" or any commit message that does not reference a ticket number in our task management system.

Is there a social or technical solution to this?

Further information: this is a maintenance project, so there's a bunch of "had to do A then B then C and then D and then finally got to implement X" tasks happening.

More information: the particular commit message that raised a flag with the manager was close to "included a better way to X, Y and Z" which is more of a refactoring message rather than a simple stylistic fix.


问:
Simple TimeZones
I need to send out emails based on a timestamp. But the timestamp must be what the user expects it to be.

The timestamp is set by the user submitting an object.

E.g

Al from L.A in the U.S saves an object with a timestamp of '3/30/2015 10:00:00AM'.

Lars from Berlin in Germany saves an object with the timestamp of '4/15/2015 11:00:00PM'.

The system that looks at these objects and later sends out emails is based in a GMT+1 timezone.

My thought, to keep it super simple, is to add or subtract the difference in the timezone hours, based on where the object is from (timezone).

So in Al's example the system would subtract 9 hours (GMT+1 difference) but in Lars' example the system would keep the date, since Germany is also GMT+1.

Wouldn't that be an ok soultion ?

答:
The web server is saving the data, not the user, so it doesn't matter what the user's time is.  The object should be saved with a timestamp in GMT (universal) time format.  Save the user's GMT timezone offset, Then add that offset to the timestamp (which is in UTC) to present to the user, his own local time.

For example, since I'm in CA, my UTCTimeZoneOffset would be -8.  Add -8 to 21:00UTC and for me, it's 13:00PST.

Title: Simple TimeZones


问:
PHP: is read file at every page load too heavy?
In F3 Framework Controller I wrote a function checking whether MySql data are saved in a file, otherwise loading a form to ask users for that data (similar to Wordpress Installation).

This function is loaded every time that a page / method is called:

```<code>abstract class Controller
{

    /* F3 */
    protected $f3;
    protected $file_configuration = 'setup.cfg';

    function __construct()
    {
        $f3 = Base::instance();
        $this->f3 = $f3;
        $this->setDatabase();
        $this->setup();
    }
}
</code>```

and setDatabase() is a simple:

```<code>private function setDatabase()
    {
        $search = 'TEST';
        $file = $this->file_configuration;
        // Read from file
        $lines = file('app/config/'.$file);
        $found = false;
        foreach($lines as $line)
        {
            // Check if the line contains the string we're looking for, and print if it does
            if(strpos($line, $search) !== false)
            {
                $found = true;
            }
        }
        if ($found===false)
        {
            $fh = fopen('app/config/'.$file, 'a') or die("can't open file");
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 1";
            fwrite($fh, $stringData);
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 2";
            fwrite($fh, $stringData);
            fclose($fh);
        }
    }
</code>```

(Please don't see the values of variables... only test at the moment) ;-)

My question is:

Others classes start extending Controller, will I put too much strain on my server reading every time the file?

Can you hint me a best approach?

Imagine wordpress: I think that every time you call the page, it checks if database exists / is properly configured, otherwise stop / ask for insert connection data (username, password, etc)

答:
Could be (too) heavy for my server performs that check every time?

This is just not good practice in general. If you end up working with other developers and they inherit from Controller as well (which seems like a very centric object in your domain) you will end up with a lot of heavy processing on your server.

I would suggest only setting things in your constructor that help you create the object. Reading things from the database doesn't seem to be a part of it.

This will also make testing a pain in the neck for you.

If you really need to do it in the constructor for some reason then I would suggest using the Singelton Pattern and only create it once. This way you can use its instance without recalling the constructor each and every time.


问:
Too specific of namespacing/packaging
I'm about to start building a C# library for English and French morphology as a side project. The library will be later merged with other linguistic aspects (phonology, sentence parsing, etc). for other languages (Japanese and Russian).

Unfortunately, I have come across an issue in my design: my namespace hierarchy is a little crazy (in my opinion).

Here's the namespace for English sentence parsing (lexing stage):

Linguistics.English.Syntax.Parsing.Lex

The above namespace would include the necessary classes for using an existing English lexicon to parse a particular text.

The Japanese equivalent would be:

Linguistics.Japanese.Syntax.Parsing.Lex

They would be separate because the lexing process for each language is different. A more extreme example of the indicative present for French verb conjugations (inflections) would be:

Linguistics.French.Inflection.Verb.Indicative.Present

I know that I can just do using Linguistics.French.Inflection.Verb if I'm working on generating verb conjugation tables, but is the organization too specific?

More specifically, if/when do namespaces become too-specific? Am I being silly or is my concern actually a potential problem?

答:
Having the language (eg, English, French, Japanese) so far up in your namespace is a smell.  If I were you I'd keep the Language identifiers in the class names only.

The recommended structure for a namespace is something like

```<code><company>.<project>.<namespace>.<subNamespace>.<andSoOn>
</code>```

So, in your case, you might consider something like:

```<code>CC.Linguistics.Syntax.Parsing.Lex
</code>```

In which you would have the classes EnglishLexicon, ItalianLexicon, etc.

Title: Too specific of namespacing/packaging

Body:
Having the language (eg, English, French, Japanese) so far up in your namespace is a smell.  If I were you I'd keep the Language identifiers in the class names only.

The recommended structure for a namespace is something like

<company>.<project>.<namespace>.<subNamespace>.<andSoOn>

So, in your case, you might consider something like:

CC.Linguistics.Syntax.Parsing.Lex

In which you would have the classes EnglishLexicon, ItalianLexicon, etc.


答:
Database servers are really good at caching small frequent queries.  It's opening a database connection that can take some time. However, if most of your requests end up hitting the database for other reasons then you really have not lost anything.

Still, this does seem to be the sort of thing you would store in a session.

Title: PHP: is read file at every page load too heavy?

Body:
In F3 Framework Controller I wrote a function checking whether MySql data are saved in a file, otherwise loading a form to ask users for that data (similar to Wordpress Installation).

This function is loaded every time that a page / method is called:

```<code>abstract class Controller
{

    /* F3 */
    protected $f3;
    protected $file_configuration = 'setup.cfg';

    function __construct()
    {
        $f3 = Base::instance();
        $this->f3 = $f3;
        $this->setDatabase();
        $this->setup();
    }
}
</code>```

and setDatabase() is a simple:

```<code>private function setDatabase()
    {
        $search = 'TEST';
        $file = $this->file_configuration;
        // Read from file
        $lines = file('app/config/'.$file);
        $found = false;
        foreach($lines as $line)
        {
            // Check if the line contains the string we're looking for, and print if it does
            if(strpos($line, $search) !== false)
            {
                $found = true;
            }
        }
        if ($found===false)
        {
            $fh = fopen('app/config/'.$file, 'a') or die("can't open file");
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 1";
            fwrite($fh, $stringData);
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 2";
            fwrite($fh, $stringData);
            fclose($fh);
        }
    }
</code>```

(Please don't see the values of variables... only test at the moment) ;-)

My question is:

Others classes start extending Controller, will I put too much strain on my server reading every time the file?

Can you hint me a best approach?

Imagine wordpress: I think that every time you call the page, it checks if database exists / is properly configured, otherwise stop / ask for insert connection data (username, password, etc)


问:
Design question concerning proper and practical encapsulation
I have been working on refactoring old code and found a lot of instances of the following type of situation: There is a master object which we call "Application" and there is only one of these. The Application will create other objects called "Features" inside it depending on user input etc. The Feature object may have some methods that take void parameters but actually operate on or use some variables in the scope of Application. This is because the functions defined in class Feature are defined in the same project and include the header from Application (this is C++). Here is a rudimentary attempt to show a simple example pseudocode:

```<code>int main()
{
    Application theApp = new Application()

    the.App.someSetting = foo;
    the.App.someVariable = bar;

    the.App.RunSomeFeature();
}
// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature();

    feature.SomeFunction(void)
}
// SomeFunction def in class Feature
void Feature::SomeFunction(void)
{
    // global variable from Application "creeping in"
    someLocalVariable = theApp.someSetting;
    otherLocalVariable = theApp.someVariable;
}
</code>```

I hope this illustrates somewhat what I mean. My goal is essentially to move the class "Feature" to some location outside the namespace of "Application" (to a dll for example) and I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated. This may be a C++ thing for all I know that it is easy (or posible) to make this coding mistake but I am not sure.

This made me think of a few questions regarding OOP design. Well designed OOP code would only have completely autonomous classes and functions with all outside variables explicitly passed in? Even if one object will be created inside another? I can see that way the entire code would be much easier to internally "reshuffle". But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise. But code written as in the example implicitly joins class Application and Feature to the same overall "block" or scope and it takes line by line work sometime to separate them.

However the other extreme would be that each class is essentially almost an autonomous application in its own right (and this may go somewhat against the idea of inheritance). When I read about OOP design principles, I usually don't find this particular nuance talked about much or I just get the idea that everything should be basically autonomous but I find that in practice this is rarely truly so.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?

答:
What you are after is not very specific for OOP, and has absolutely nothing to do with inheritance. You are after proper modularization. Each of your features should be a component, that means either a single class, or a group of classes, with a well defined interface, and not directly dependent on the Application object.

In the current situation each feature depends on Application, and Application depends on each feature, so every feature depends essentially on every other feature, which makes it impossible to test single features in isolation. Eliminating the direct dependencies of the features from the Application object and passing data in and out through the components interfaces will change that situation. If you do this right, you will end up with lots of independent components, where you can change and test each of it independently from each other, with a much lower risk of breaking your program when you are going to change something.


问:
Optimizing XML based protocol
We have recently replaced binary based communication protocol with XML one (between browser based client and server). The implementation is almost complete, however I am looking for ways to improve its performance both for faster transmission and parsing. Any ideas ? Please post link along with the answer.</p>

答: Use compression if you have the needed computing power on both ends.</p>

Title: Optimizing XML based protocol


答:
I think it's perfectly OK for a "feature" to need an "application", but the use of globals is nauseating. Constructor dependency injection can solve this problem, and allow a gradual refactoring of code.

(I'm not a C++ developer, so any corrections/clarifications are welcome)

First, the Application class:

```<code>class Application
{
public:
    void run_blog_feature();
};

Application::run_blog_feature() {
    BlogFeature blog(this);

    blog.run();
}
</code>```

The BlogFeature class has a constructor allowing the application to pass itself in:

```<code>class BlogFeature
{
private:
    int some_setting = 0;
public:
    BlogFeature(Application app);
    void run();
};

BlogFeature::BlogFeature(Application app) {
    this->some_setting = app.get_some_setting();

    // more initialization
};

BlogFeature::run() {
    // do stuff
};
</code>```

That way the "features" can configure themselves based on the application. Furthermore, you can refactor the application feature by feature in isolation. Gradually you refactor the code relying on globals into code relying on constructor injection.

You could then refactor it further and split the application configuration into its own class, and then just pass the config object into the features to provide further decoupling.

As a final step, you can create a "factory object", and provide it with some configuration. The factory object would have a method that returns the "feature" objects. All configuration of the features happens within the factory object, leaving your "features" and the application ignorant of the configuration layer.

Title: Design question concerning proper and practical encapsulation

Body:
I have been working on refactoring old code and found a lot of instances of the following type of situation: There is a master object which we call "Application" and there is only one of these. The Application will create other objects called "Features" inside it depending on user input etc. The Feature object may have some methods that take void parameters but actually operate on or use some variables in the scope of Application. This is because the functions defined in class Feature are defined in the same project and include the header from Application (this is C++). Here is a rudimentary attempt to show a simple example pseudocode:

```<code>int main()
{
    Application theApp = new Application()

    the.App.someSetting = foo;
    the.App.someVariable = bar;

    the.App.RunSomeFeature();
}
// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature();

    feature.SomeFunction(void)
}
// SomeFunction def in class Feature
void Feature::SomeFunction(void)
{
    // global variable from Application "creeping in"
    someLocalVariable = theApp.someSetting;
    otherLocalVariable = theApp.someVariable;
}
</code>```

I hope this illustrates somewhat what I mean. My goal is essentially to move the class "Feature" to some location outside the namespace of "Application" (to a dll for example) and I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated. This may be a C++ thing for all I know that it is easy (or posible) to make this coding mistake but I am not sure.

This made me think of a few questions regarding OOP design. Well designed OOP code would only have completely autonomous classes and functions with all outside variables explicitly passed in? Even if one object will be created inside another? I can see that way the entire code would be much easier to internally "reshuffle". But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise. But code written as in the example implicitly joins class Application and Feature to the same overall "block" or scope and it takes line by line work sometime to separate them.

However the other extreme would be that each class is essentially almost an autonomous application in its own right (and this may go somewhat against the idea of inheritance). When I read about OOP design principles, I usually don't find this particular nuance talked about much or I just get the idea that everything should be basically autonomous but I find that in practice this is rarely truly so.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?

Body:
I think it's perfectly OK for a "feature" to need an "application", but the use of globals is nauseating. Constructor dependency injection can solve this problem, and allow a gradual refactoring of code.

(I'm not a C++ developer, so any corrections/clarifications are welcome)

First, the Application class:

class Application
{
public:
    void run_blog_feature();
};

Application::run_blog_feature() {
    BlogFeature blog(this);

    blog.run();
}

The BlogFeature class has a constructor allowing the application to pass itself in:

class BlogFeature
{
private:
    int some_setting = 0;
public:
    BlogFeature(Application app);
    void run();
};

BlogFeature::BlogFeature(Application app) {
    this->some_setting = app.get_some_setting();

    // more initialization
};

BlogFeature::run() {
    // do stuff
};

That way the "features" can configure themselves based on the application. Furthermore, you can refactor the application feature by feature in isolation. Gradually you refactor the code relying on globals into code relying on constructor injection.

You could then refactor it further and split the application configuration into its own class, and then just pass the config object into the features to provide further decoupling.

As a final step, you can create a "factory object", and provide it with some configuration. The factory object would have a method that returns the "feature" objects. All configuration of the features happens within the factory object, leaving your "features" and the application ignorant of the configuration layer.