问:
Handling insertion to database with Repository pattern
I have a design question for working with databases in object-oriented PHP.

I have a table in my database called products. Then I have 2 classes for this table in my PHP project. ProductsRepository.php and Product.php.

ProductsRepository.php currently looks like this

```<code>class ProductsRepository
{

    private $db;

    public function __construct(DB $db)
    {
        $this->db = $db;
    }

    public function getById($id)
    {
        $data = $this->db->GetProductByID($id);

        $product = new Product(
            $data['id'],
            $data['category'],
            $data['title'],
            $data['description'],
        );

        return $product;
    }

    public function getAll()
    {
        $products = array();
        $data = $this->db->GetAllProducts();
        foreach ($data as $productData){
            $product = new Product(
                $productData['id'],
                $productData['category'],
                $productData['title'],
                $productData['description'],
            );
            $products[] = $product;
        }

        return $products;
    }
}
</code>```

My question is how I should build a "createProduct" method. First and foremost, which class should it be in? I want the method to return an instance of the new product. The main problem I have with this is how I should handle the id of the new product since it will be given the next id available by the database.

A few options I've thought of:

Have createProduct in ProductsRepositoryand let it take a product with id set to -1 as argument

```<code>public function createProduct(Product $product)
{
    $product['id'] = $this->db->insertANewProduct($product); //returns the id
}
</code>```

Have createProduct in Product

Should this be the constructor for the Product class?

```<code>public function createProduct($db, $data)
{
    $this->$data = $data; //includes all info of the new product except the id
    $this->$data['id'] = $db->insertANewProduct($data); //returns the id
}
</code>```

答:
```<code>$this->$data['id'] = $db->insertANewProduct($data);
</code>```

I think is a bad practice, because breaks de Single Responsibility Principle, the product class knows it's been persisted. You are loosing what you win with the repository pattern.
If you want to do that another option (less OO) is Active Record.

I would choose the option 1

```<code>    public function createProduct(Product $product){
       $product['id'] = $this->db->insertANewProduct($product);
       return $product;
    }
</code>```

I really work in Java and use JPA for persistence my entities, in this case that you have auto generated id the JPA implementation (i.e. Hibernate) will populate the object id for you.
Have you considered use a ORM?

Body:
$this->$data['id'] = $db->insertANewProduct($data);

I think is a bad practice, because breaks de Single Responsibility Principle, the product class knows it's been persisted. You are loosing what you win with the repository pattern.
If you want to do that another option (less OO) is Active Record.

I would choose the option 1

    public function createProduct(Product $product){
       $product['id'] = $this->db->insertANewProduct($product);
       return $product;
    }

I really work in Java and use JPA for persistence my entities, in this case that you have auto generated id the JPA implementation (i.e. Hibernate) will populate the object id for you.
Have you considered use a ORM?


问:
Using variable + method invocation or repeating invocation?
Here is two methods that does the same thing. One is repeating the call to the method Print where the other one does not but has an additional variable.

```<code>class Program
{
    static void Main(string[] args)
    {
        Snippet1(args);
        Snippet2(args);
    }

    private static void Snippet1(string[] args)
    {
        string message;
        if (args.Length == 0)
        {
            message = "No argument";
        }
        else
        {
            message = string.Format("Argument Count = {0}", args.Length);
        }
        Print(message);
    }

    private static void Snippet2(string[] args)
    {
        if (args.Length == 0)
        {
            Print("No argument");
        }
        else
        {
            Print(string.Format("Argument Count = {0}", args.Length));
        }
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
</code>```

I personally do not like having the same invocation twice and prefer to use a variable which make the if statement goal to define the message instead of defining + invoking. I also believe that it's more clear to have an unique invocation if this one need to be changed later.

What is the best practice/pattern that should be applied?

答:
Tomorrow your boss will tell you that they want to have most of the messages in RED color and a few in BLUE with extra padding... and you are pretty much into major refactoring with both of your approaches.

Your Program class is responsible for decision making and printing at the same time. That way Single Responsibility Principle has been broken.

So, I would add even more separation of concerns:

```<code>class Program {
    public static void Main(string[] args) {
        var simplePrinter = new SimplePrinter();
        var errorPrinter = new ErrorPrinter();

        var objectWithError = new MyObject(errorPrinter);
        objectWithError.DoSomething();

        var simpleObject = new MyObject(simplePrinter);
        simpleObject.DoSomething();
    }
}

public interface IConsolePrinter {
    void Print(string s);
}

public class SimplePrinter : IConsolePrinter {
   public void Print(string s) {
       Console.WriteLine(s);
   }
}

public class ErrorPrinter : IConsolePrinter {
   public void Print(string s) {
       Console.WriteLine(String.Format("**** ERROR: {0}", s));
   }
}

public class MyObject {
    private ConsolePrinter _printer;

    public MyObjectThatUsesConsolePrinter(IConsolePrinter printer) {
        _printer = printer;
    }

    public void DoSomething() {
        _printer.Print("Love OOP! Respect Single Responsibility Principle!");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Tomorrow your boss will tell you that they want to have most of the messages in RED color and a few in BLUE with extra padding... and you are pretty much into major refactoring with both of your approaches.

Your Program class is responsible for decision making and printing at the same time. That way Single Responsibility Principle has been broken.

So, I would add even more separation of concerns:

class Program {
    public static void Main(string[] args) {
        var simplePrinter = new SimplePrinter();
        var errorPrinter = new ErrorPrinter();

        var objectWithError = new MyObject(errorPrinter);
        objectWithError.DoSomething();

        var simpleObject = new MyObject(simplePrinter);
        simpleObject.DoSomething();
    }
}

public interface IConsolePrinter {
    void Print(string s);
}

public class SimplePrinter : IConsolePrinter {
   public void Print(string s) {
       Console.WriteLine(s);
   }
}

public class ErrorPrinter : IConsolePrinter {
   public void Print(string s) {
       Console.WriteLine(String.Format("**** ERROR: {0}", s));
   }
}

public class MyObject {
    private ConsolePrinter _printer;

    public MyObjectThatUsesConsolePrinter(IConsolePrinter printer) {
        _printer = printer;
    }

    public void DoSomething() {
        _printer.Print("Love OOP! Respect Single Responsibility Principle!");
    }
}


答:
A competent production-quality industrial-strength compiler, with optimization turned on, will automagically transform Snippet2 into Snippet1.  If your compiler falls into that category (and most do), there's no real reason for a preference.

Personally, being one who believes in being terse, I'd've coded it as:

```<code>private static void Snippet3(string[] args)
{
    Print((args.Length != 0)?string.Format("Argument Count = {0}",
                                           args.Length)
                            :"No argument");
}
</code>```

(assuming that Java allows the ternary operator...)

Title: Using variable + method invocation or repeating invocation?

Body:
Here is two methods that does the same thing. One is repeating the call to the method Print where the other one does not but has an additional variable.

```<code>class Program
{
    static void Main(string[] args)
    {
        Snippet1(args);
        Snippet2(args);
    }

    private static void Snippet1(string[] args)
    {
        string message;
        if (args.Length == 0)
        {
            message = "No argument";
        }
        else
        {
            message = string.Format("Argument Count = {0}", args.Length);
        }
        Print(message);
    }

    private static void Snippet2(string[] args)
    {
        if (args.Length == 0)
        {
            Print("No argument");
        }
        else
        {
            Print(string.Format("Argument Count = {0}", args.Length));
        }
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
</code>```

I personally do not like having the same invocation twice and prefer to use a variable which make the if statement goal to define the message instead of defining + invoking. I also believe that it's more clear to have an unique invocation if this one need to be changed later.

What is the best practice/pattern that should be applied?

Body:
A competent production-quality industrial-strength compiler, with optimization turned on, will automagically transform Snippet2 into Snippet1.  If your compiler falls into that category (and most do), there's no real reason for a preference.

Personally, being one who believes in being terse, I'd've coded it as:

private static void Snippet3(string[] args)
{
    Print((args.Length != 0)?string.Format("Argument Count = {0}",
                                           args.Length)
                            :"No argument");
}

(assuming that Java allows the ternary operator...)


问:
Control Start Of Program
I made a program, which was supposed to run every night as a windows scheduled task, let's say the program is just one method, called Do_Task(). Usually you need to press a button to run the Do_Task() method, but In order for it to run as a scheduled task, I had to call the Do_Task() method in the form loading event. (Can't tell windows scheduler to press a button).

But here is the problem: when I install it by the end user, I want to have the option of either automatic (Do_Task() gets called from the from loading event), or Manuel (Do_Task() runs only from a button). In order to do testing and change settings in config file.

I tried to implement it via a check-box and an application property, to specify how the program should run the next time it runs. In the form loading event, I made an IF statement checking, if run auto is true then set application property run auto as true and run Do_Task(), etc etc.

But it didn't work, It kind of ignored me and always Ran on auto. What am I missing? I suspect (from other problems I encountered with this issue) that the form loading event is too late for these kind of stuff, so what is the earliest place you can issue commands to your program.

答:
Split your task logic and view logic

It sounds like your program has the task logic intermingled inside the same class which handles displaying a dialog.

A better idea would be to break this functionality up into separate classes, each of which handles one responsibility.  At minimum, you should have one which handles displaying the dialog and one for performing your task (i.e., your Do_Task() method, which should also probably be renamed to something more specific about the actual task performed).

Once you split things up, you can more easily do what Deduplicator suggested in the comments: provide a command-line option for when you need to run the task unattended.  It will be as simple as creating the view class and passing the task class to it for interactive mode and simply creating the task class and running Do_Task for unattended mode.

Title: Control Start Of Program


问:
Why isn't programming mobile apps more similar to programming desktop applications?
Well, first of all I don't really know how the hardware of a smartphone is, and I've just programmed for Android. But it feels safe to think that a smartphone is just an old PC with some particular things, but an old PC anyway, I think even the worst smartphone today likely has more power than the an standard PC equiped with the first Pentium 4, and that if Android uses those premises for programming so it would be in Iphone, Windows phone and the like.

So, why is its programming so different? I mean, I could write lots of medium sized desktop application programs with any language for that use, and I could hardly notice the difference between running the program in a brand new PC or an old Pentium 4 computer, yeah some mobile apps are big and might require better resource management, but those aren't a lot.

I personally find mobile apps would be easier to program this way and that it would be the most logical way for them to have been developed, in fact I don't think they should have a problem to execute any program that for example executes in windows, yeah I know operating system is far from being the same, but support could be included  for those programs, as I guess mobile phones have enough power to run lots of them.

Is there any failure in my reasoning? Which one? If not, why may they not make it as it's on desktop programming?

Thank you.

答: Think of all the hardware a phone has that a typical PC doesn't have! Cellular radio, accelerometers, GPS, touch screen, and a tiny battery with very limited power. Even if you don't use any of that hardware, you are writing your software for a GUI that is optimized for touch devices with a small screen. Microsoft tried to push having a similar GUI on phone and desktops (Windows 8), and it was widely rejected.</p>


答:
Like Charles E Grant mentions - there's a lot of hardware on a phone that your average PC doesn't have.

However, even if we discount all that - the system architecture of a smartphone is very different to that of an IBM compatible PC. Different processors mean different instruction sets. There's also the issues of the very low power available to phone electronics compares to your old PCs.

And then there's the user interface - touch (and multi-touch) is very different to keyboard/mouse. The screen on a phone is much smaller - it may have the same resolution (or better) as compared to VGA, but VGA monitors were physically bigger.

And then you have very different OS: iOS, Android, and Windows Mobile are different to their desktop cousins.

Chances are, though, you've just used the default development framework for Android - and this can make it seem even more different to PC application development.

There are software tools out there to help developers with cross-platform development - frameworks like Qt (C++) and Xamarin (C#) abstract the differences between mobile and desktop app development.

Title: Why isn't programming mobile apps more similar to programming desktop applications?

Body:
Well, first of all I don't really know how the hardware of a smartphone is, and I've just programmed for Android. But it feels safe to think that a smartphone is just an old PC with some particular things, but an old PC anyway, I think even the worst smartphone today likely has more power than the an standard PC equiped with the first Pentium 4, and that if Android uses those premises for programming so it would be in Iphone, Windows phone and the like.

So, why is its programming so different? I mean, I could write lots of medium sized desktop application programs with any language for that use, and I could hardly notice the difference between running the program in a brand new PC or an old Pentium 4 computer, yeah some mobile apps are big and might require better resource management, but those aren't a lot.

I personally find mobile apps would be easier to program this way and that it would be the most logical way for them to have been developed, in fact I don't think they should have a problem to execute any program that for example executes in windows, yeah I know operating system is far from being the same, but support could be included  for those programs, as I guess mobile phones have enough power to run lots of them.

Is there any failure in my reasoning? Which one? If not, why may they not make it as it's on desktop programming?

Thank you.


问:
Strategy to define domain data used in Integration Tests
In my job we work in a data driven web application and performance is a important business feature. So, queries in the model tier are frequently large
and contain much of the business logic. As a result we have many Integrations Tests that rely in XML datasets used by our test framework(an abstraction to DbUnit) to populate data model. We have migration scripts containing DDL and data domain changes that are executed before all tests, but the framework clean all tables before the execution of each test. We are considering changing this behavior and do not clean domain tables anymore.
We would continue defining application data specific to the tests in each XML dataset, but regarding the domain data:

Should we continue defining it in each XML dataset too?

Pros:

Tests will not break in case of domain data changes that do not
impact business logic.

We can define a small subset of domain data
sufficient to test business logic.

Cons:

It may be necessary create too many tables and rows to represent all relationships that the test need.

It would be expensive to fix datasets in case of changes in the data model.

Data duplication in many XML datasets in the project.

Should we do not clean the domain data inserted by the scripts? These scripts would execute
only one time before all Integration Tests and the data would be common to all tests.

Pros:

Tests will break in case of domain data changes that impact business logic.

It would be easier to create data to the test, because we only need to create application data.

Cons:

Tests may break in case of domain data changes that do not impact business logic. We should be careful to not test things like number
of rows returned or text attributes of domain entities.

If to test some business logic we need specific characteristics of the domain data that we cannot assume it is true in production, we
need to change  the actual data domain before the execution of the
test and rollback in the end. But how change something that is
mutable and unpredictable?

答:
My suggestion is a mix:

1st step: Run integration test in a clean database, populated and discarded on each execution. This way you test your code with the lasts version of your database model.

2nd step, when you want to pick a release candidate from the step 1, because you want to promote it (and you don't usually promote every candidate), then you run the full integration tests in a production like database. You test your migration scripts and the integration of your code to the production environment.


问:
What exactly is "Web API" in ASP.Net MVC4?
I know what a Web API is.

I've written API's in multiple languages (including in MVC3).

I'm also well practiced in ASP.Net.

I just discovered that MVC4 has "Web API" and without going through the video examples I can't find a good explanation of what exactly it IS.

From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything "easier".

Can someone please explain to me what Web API in MVC4 is exactly?  Why do I need it?  Why can't I just write my own API?

答:
Today, a web-based application is not enough to reach it's customers. People are very smart, they are using iphone, mobile, tablets etc. devices in its daily life. These devices also have a lot of apps for making the life easy. Actually, we are moving from the web towards apps world.
So, if you like to expose your service data to the browsers and as well as all these modern devices apps in fast and simple way, you should have an API which is compatible with browsers and all these devices.</p>


问:
Mobile applications in Delphi
Many of us know that Delphi executables are little bit gigantic, but again it is acceptable as nowadays 1.5 mb is not a big issue in PC.

But what about mobile devices? Currently Firemonkey supports iOS and in the near future it is going to Android and so on. Isn't 4 mb of executable size for mobile devices is too much for a simple application?

Will Delphi team try to reduce the size of executable in the future OR is it possible to do without loosing most of the features in Firemonkey?

答:
You can answer this question yourself, by simply browsing any mobile store in... games category!

You'll quickly learn, that application size of 50-150 MB is nothing for both mobile device and user, if only application is worth installing and using (is usable in case of your application or have a good gameplay and marketing, in case of game). If you convince user, that installing your app is worth, he or she will install it no matter, if it takes 4 MB or 40 MB.

Please note, that the fact, that I'm answering in middle of 2015 (3,5 years after asking your question) and possible hardware expansion / growth during this period of time, has nothing to do with this. Even in time of asking this question (end of 2011) apps like Facebook or Google+ had around 50 MB of size and everyone was installing them, because they were Facebook or Google+, i.e. because people wanted to have them, not even thinking about application size or device performance.

You should also notice another thing. It is quite obvious, that people, who are installing apps from mobile stores doesn't even care for the requirements particular application has (and thus so many dumb user's devices are infected by bad software). If they don't even check requirements, how can we think, that they'll ever matter about app size? I can imagine (purely theoretical numbers, no source), that if only 25% of users spares 2-3 seconds to check app requirements (or think, if it can do any harm to the device) then number of users, who are actually checking application size (or care about this at all) is around 5-10%, so close to statistical error.

If only your application is interesting to end user, he or she most likely won't take much care or won't care at all about your application size. And thus you shouldn't care much about it.

Title: Mobile applications in Delphi


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
To all the people who answered NO, your Goals were probably NOT SMART enough.

I have used them and I find them incredibly useful. You might want to try something that works for us:

Set Quarterly Goals.

Set measurable goals.

Set only one goal for the individual

Make the individual accept the goal, if he says the Goal is too ambitious readjust till the time when both of you agree.

At the End of the quarter, come up with a Boolean value. Goal achieved = true or false.

This is extremely powerful, it creates accountability  for the Developer. The people who want to find excuses chicken out after 6 months or so.

P.S : I can understand people down voting the answer but please drop in a relevant comment atleast I wil learn something I dont know :-)

Title: Are SMART goals useful for programmers?

ContentLicense: CC BY-SA 2.5


问:
Good practice to hold Constants in their own file?
I've noticed some projects like to store constants in their own file, i.e constants used globally and in the main program loop might clutter the main file so perhaps they look to place them elsewhere and then reference/import file/class.

I understand that when writing an OOP class that you'd want to keep all constants at the header of the class file so they can be referenced statically as such:

```<code>myCar.setColour(Colour.RED);
</code>```

Where RED is a colour constant in the Colour class.

What is good practice for having a large amount of constants, should they just be at the top of your main file or is it in any way wise to have maybe a ProgramConstants class that is purely static, public and available to read?

答:
The idea behind encapsulation in object-oriented programming is moving data and the code that uses it together.

There is no "but the data are constants, treat them specially." If you have colors, keep them in a Color class. Java's Calendar class has calendar field constants in it. BigDecimal and BigInteger each contain constants of their own type.

The idea is that referencing constants involves their scope: BigDecimal.ZERO for example. I know that is a decimal zero because I typed BigDecimal.ZERO and not BigInteger.ZERO.

One of the worst anti-patterns in this regard is having a "constant interface" which is honestly lazy and unclear. Sometimes you come across an interface containing a bunch of random constants thrown together, and classes will implement the interface just to make it easy to refer to the constants. That generally ends up violating LSP and makes it difficult to determine what those constants do.

Constants should be:

An enum if appropriate, such as java.math.RoundingMode. The Java Calendar fields which were created before enum existed should be an enum. This necessarily scopes them properly and ensures other constants are not in the same namespace (class static final field).

Located on the class that defines their type, if appropriate. This covers the reusable numbers on BigDecimal for example.

Located somewhere else where like constants are together and not intermingled with other, unlike constants.

One could argue this is a matter of opinion. I feel that if you asked any group of experts to compare e.g. BigDecimal and some random AWT constants class, we would come to a consensus that there are some really bad practices in reality and some that make code clearer and easier to understand.


问:
MVC content management framework with an admin panel
I've lately been developing my own MVC content management system using PHP and, at least in my mind, am a little stuck with the system design. I believe this would apply to building a content management system with an existing MVC framework as well.

This is going to be a little difficult to explain, so sorry in advance for the lengthy dilemma.

A little intro to the system:

Currently my routes look a little like this (stored as JSON):

```<code>{
    "/admin/:controller/:action/:params":"",
    "/admin/:controller/:params":"AdminController",
    "/admin":"AdminController",
    "/:page?/:subpage?":"IndexController"
}
</code>```

The routes are the keys, the default controllers are the values. If there isn't a default controller the router falls through to the next rule. I've done this to separate the front end of the site from the admin panel.

The controllers are all in one directory for the time being, although this is destined to change. They either return a template that's been populated with data from their respective model or simply modify the request they were instantiated with.

The problem:

My problem is with deciding how to implement separate controllers that concern the same model for the front end and the back end in a modular way.

For example, I have a page in the admin panel that allows an administrator to enter some private information that's intended only to be accessible on the front end with a username and password. Imagine this is handled by an InfoController in the back end, for editing the private information, matched by the route /admin/info.

What if I wanted to create a route for the front end, for accessing the private information, with the same name as in the admin panel (/info)?

The problem makes more sense in context with the solutions I've considered, I think.

Solutions I've considered:

My first thought was to append all admin-related controllers with
Admin - so AdminInfoController and InfoController - but I'm
interested in eventually having a modular system where all the routes,
controllers and views (and CSS/JavaScript if needed) pertaining to the Info model would be in their own directory structure (something like /modules/info).

With the desire for modularity in mind, I thought about matching routes a bit like /:module/:controller/:action, but this would then imply that the admin panel is itself a module, which would need access to all the modules the front end can use. Would that make sense?

The design I've thought about the most is to have the admin and front end as two distinguished, core concepts of the framework. They would share modules that contain controllers and views for both.

Ultimately I'm looking for input on the best approach here, any alternatives, and whether I'm totally over-thinking this.

It feels a bit like I've driven myself crazy with the pursuit of my ideal system design that keeps with the MVC pattern (is it even the right thing for a system like this?). Thanks for reading, I hope it made sense.

答:
I solved this when I started using service providers with a dependency injection container to implement a module system.

Treating modules as service providers for the application is what worked best, whether they are providing new services or providing to data to existing services, like routes.

The admin panel has itself become a module that simply provides admin related routes and services to the container. Any other modules can do the same thing.

Default routes in the config look like this in JSON format:

```<code>{
    "/:controller/:action/:params": {
        "namespace": "Darya\\Core\\Controllers"
    },
    "/:controller/:params": {
        "namespace": "Darya\\Core\\Controllers"
    },
    "/:page?/:subpage?": "Darya\\Core\\Controllers\\IndexController"
}
</code>```

Module routes can look like this when defined in a module class (a service provider):

```<code>// Route path to namespace prefixes:
// "/admin/info" would become "Darya\Module\Admin\Controllers\InfoController"
$router->add(array(
    '/admin/:controller/:action/:params'  => 'Darya\Module\Admin\Controllers',
    '/admin/:controller/:params'          => 'Darya\Module\Admin\Controllers',
    '/:controller/:action/:params'        => 'Darya\Module\Controllers'
    '/:controller/:params'                => 'Darya\Module\Controllers'
));
</code>```

This way all the URLs of the application are nice and extensible. The next problem is deciding on route priorities, but that becomes off topic.

Dependency injection is your friend. :)

Body:
I solved this when I started using service providers with a dependency injection container to implement a module system.

Treating modules as service providers for the application is what worked best, whether they are providing new services or providing to data to existing services, like routes.

The admin panel has itself become a module that simply provides admin related routes and services to the container. Any other modules can do the same thing.

Default routes in the config look like this in JSON format:

{
    "/:controller/:action/:params": {
        "namespace": "Darya\\Core\\Controllers"
    },
    "/:controller/:params": {
        "namespace": "Darya\\Core\\Controllers"
    },
    "/:page?/:subpage?": "Darya\\Core\\Controllers\\IndexController"
}

Module routes can look like this when defined in a module class (a service provider):

// Route path to namespace prefixes:
// "/admin/info" would become "Darya\Module\Admin\Controllers\InfoController"
$router->add(array(
    '/admin/:controller/:action/:params'  => 'Darya\Module\Admin\Controllers',
    '/admin/:controller/:params'          => 'Darya\Module\Admin\Controllers',
    '/:controller/:action/:params'        => 'Darya\Module\Controllers'
    '/:controller/:params'                => 'Darya\Module\Controllers'
));

This way all the URLs of the application are nice and extensible. The next problem is deciding on route priorities, but that becomes off topic.

Dependency injection is your friend. :)


问:
Unit testing text output
I have recently become responsible for a legacy tool that analyses code and provides a log as output. As part of the JUnit suite for this, there are ~100 tests that rely on successfully matching the produced log with a static expected log.

Now this means that if the format of the log changes at all, it will break the unit tests. But I cannot decide if this is a good or a bad thing.

Pros:

Quickly failing unit tests let me know that something has changed

Cons:

Tests have to be updated every time the log style is changed

A straight text compare is bad for this case, because the log file involves times. So if a run doesn't take exactly as long as was expected, the test fails.

I can't help but feel that these tests shouldn't be run. But at the same time I don't want to leave the log file process uncovered.

What is the solution here? Better unit tests? No unit tests? How can I do this without my tests being so brittle?

The log is being written to a file, and is not part of any logging framework (a file is generated after the tool runs, telling the user which files failed validation and why).

答:
Short-term solution: Leave things as they are. Badly written, brittle tests are much, much better than not having tests. On a scale from "no tests" to "tests so reliable they make you weep and do all your work for you", your existing test suite is much closer to "weep" than to "nothing".

Middle-term solution: refactor. It's inconceivable that the analysis tool doesn't have an intermediate representation of its findings, before it's turned into a stream of text. Make that representation publicly accessible and rewrite the tests to assert things about that representation, not about the textual form. It sucks, but you only have to do it once, and from then on maintenance will be much, much easier, even when logic changes and new cases are added.

Title: Unit testing text output


答:
If the format of the log changes at all, it will break the unit tests

When code changes, it breaks the corresponding unit tests. By following your logic to the extreme, you would avoid writing tests at all.

Think about the goal of those tests. Are you testing:

That a method actually logs something?

That a method uses a proper message template?

That a method uses proper values to format the message?

That a method logs a specific message (that is a message template formatted using the actual values)?

In the first three cases, you may use dependency injection (DI) to inject a logging mock or stub. On the other hand, this means more code and more complicated logic, so if you are pretty sure that log format won't change anyway in the near future, this may not be a pragmatic thing to do. Note that most logging frameworks make it very simple to substitute your own handlers during testing, which means that the actual approach may be much simpler than implementing DI.

If you're actually testing that the messages correspond to the expected ones, then the current solution responds perfectly well to the requirements. Those hundred tests are not unit tests, but functional/system tests; still, they are perfectly valid in their current form.

Consider logging as one of the outputs of the method which should be tested. Like you assert that the actual result of a method is equal to the expected value, you do in the same way the assertions about the logs. Ideally, in unit tests, the testing surface will be very small: you'll inject a logging mock and do an Assert.Equals on the messages received by the mock, in the same way you'll be testing that a method which should export data to a file actually did its job without having to actually use the file system. In functional and system tests, the testing surface may be much larger, and include the actual file system.

Title: Unit testing text output

Body:
I have recently become responsible for a legacy tool that analyses code and provides a log as output. As part of the JUnit suite for this, there are ~100 tests that rely on successfully matching the produced log with a static expected log.

Now this means that if the format of the log changes at all, it will break the unit tests. But I cannot decide if this is a good or a bad thing.

Pros:

Quickly failing unit tests let me know that something has changed

Cons:

Tests have to be updated every time the log style is changed

A straight text compare is bad for this case, because the log file involves times. So if a run doesn't take exactly as long as was expected, the test fails.

I can't help but feel that these tests shouldn't be run. But at the same time I don't want to leave the log file process uncovered.

What is the solution here? Better unit tests? No unit tests? How can I do this without my tests being so brittle?

The log is being written to a file, and is not part of any logging framework (a file is generated after the tool runs, telling the user which files failed validation and why).


答:
The underlying problem that you are encountering is that you are testing everything in one go when comparing two text files. If any little thing changes, then the entire test fails and it is indeed tedious to find the part that broke and then fix it.

You are doing system testing in jUnit.  Not that it can't do it (though there are better testing frameworks for incorporating multiple types of testing) but it is important to realize the distinction between the types of tests and what you are doing.

And yes, system tests are some of the more fragile tests that one can do.

The first step to correcting this would be instead of writing out a log file yourself, use a logging framework such as Log4J and have a custom appender write out the format you want to the final file.

By switching to a logging framework, you are then able to use different appenders for different situations. When running in test, you can have your own validation appender. This would allow you to expose the information that is sent into the logger in the tests and verify that the information is correct - that when you send this message into the logging framework, it contains this information. That is a unit test.

Another unit test would be to validate that when you send specific information into the 'to customer file' appender then the corresponding information is properly formatted in the log (and you mock the log being written so that you are not going out to hit the disk with the comparison). Each type of message is tested and the format validated. This allows you to test the format in isolation from the complete product. If the format changes, you fix it here (rather than in all the other tests).

You may wish to look at testNG which has as part of its design goals the ability to separate test suites and test phases (unit, integration, system) better than jUnit did at the time that testNG was written (jUnit has come a ways since then).  This would help you make the unit tests easier to run for developers (which makes them more likely to be run).

Title: Unit testing text output


问:
When to turn off Option Strict? Or how to deal with inheritance of COM using Option Strict?
I'm trying develop an add-in for an application using it's API and I have Option Strict turned on.  Trying to work with these COM objects is causing multiple compile issues saying

Option Strict On disallows implicit conversions from 'typeA' to
  'typeB'.

I'm currently overcoming the issue by using DirectCast, which means I have to define the type in multiple places, which makes future code maintenance kind of sucky.

A simple example is:

Dim templateMgr As IEdmTemplateMgr5 = TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr)
```

<p>The CreateUtility method returns an object which implements the interface specified by the argument (argument is an EdmUtility Enum value). </p>

<p>The return is specified at compile time as <code>System.Object</code> so must be cast to the right type in order to use it. </p>

<p>With option strict on I cannot do this implicitly, so I have been using <code>DirectCast</code> thusly:</p>

<pre class="lang-vb prettyprint-override"><code>Dim templateMgr As IEdmTemplateMgr5 = DirectCast(TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr), IEdmTemplateMgr5)
</code>```

There are many, many, many (that many!) COM members that use generic members that make the compiler very unhappy with Option Strict turned on.

I don't particularly like using DirectCast() because it means declaring the type in multiple places scattered all throughout the code.

Is this a case where it's better to just turn off Option Strict??

I feel like there has to be a better way!

EDIT 1

My compile options are:

Option Explicit = ON

Option Strict = ON

Option Infer = ON

Option Compare = Text

Target CPU = AnyCPU

EDIT 2

Here is another example that isn't just creating a new object instance.  In this example I am using a loop to get information on all the objects in an array that returned by another function.

The return from Data.Get is always type System.Object which again causes teh compiler to complain that implicit conversion from type 'Object' to type 'String' is not allowed with Option Strict on.

Dim DataReturn As System.Array
Dim refreshFlag As Long
Try
    refreshFlag = TheTemplate.RunEx(TheCommand.mlParentWnd, TheVault.RootFolderID, DataReturn)

    If Not DataReturn.IsAllocated Then Throw New Exception("Nothing was created by the template.")

    'Refresh the folder view if required
    If refreshFlag = EdmRefreshFlag.EdmRefresh_FileList Then TheVault.RefreshFolder(TheVault.RootFolderPath)

    'Return the path(s) of the newly created file(s)
    Dim path As String = String.Empty
    For Each data As EdmData In DataReturn
        Select Case data.Type
            Case EdmDataType.EdmData_File
                path = DirectCast(data.Get(EdmDataPropertyType.EdmProp_Path), System.String)
                If path.Length > 0 Then CreatedFilesPaths.Add(path)
                path = String.Empty
        End Select
    Next
```

答:
Given that you are using Option Infer On, you could create a few generic extension methods to handle your situation.

```<code>Module EX
   <Extension()> _
   Public Function CreateInstance(Of T)(ByVal Vault7Instance As IEdmVault7, ByVal typ As EdmUtility) As T
      Return DirectCast(Vault7Instance.CreateUtility(typ), T)
   End Function
End Module
</code>```

then instantiate something like this:

```<code>Dim templateMgr = TheVault.CreateInstance(Of IEdmTemplateMgr5)(EdmUtility.EdmUtil_TemplateMgr)
</code>```

Body:
Given that you are using Option Infer On, you could create a few generic extension methods to handle your situation.

Module EX
   <Extension()> _
   Public Function CreateInstance(Of T)(ByVal Vault7Instance As IEdmVault7, ByVal typ As EdmUtility) As T
      Return DirectCast(Vault7Instance.CreateUtility(typ), T)
   End Function
End Module

then instantiate something like this:

Dim templateMgr = TheVault.CreateInstance(Of IEdmTemplateMgr5)(EdmUtility.EdmUtil_TemplateMgr)

OwnerDisplayName: TnTinMn


问:
Should unit tests run on every git branch?
I am new to repo management / continuous integration.

I designed a repo in the following way

```<code>PROJ
 |-src
 |-include
 |-lib
 |-config
PROJ_Unit_Tests
 |-src
 |-config
PROJ_Doc
</code>```

When I now do continuous integration, i.e., running unit test on the build server, should they run on every branch or only on the develop branch?

If they only run on the develop branch and a feature branch going on for long, I am afraid that the developer is pushing changes to his feature branch which would actually fail the build. On the other hand, if a feature branch deactivates functionality of the develop branch, then the programmer has to manually disable to corresponding unit tests.

答:
Run your unit tests on every branch.  How do you know your code is actually working as expected otherwise? This goes the same for any other tests you may have.

You say it yourself right here, "If they only run on the develop branch and a feature branch going on for long, I am afraid that the developer is pushing changes to his feature branch which would actually fail the build".

The latter problem you're hinting at is up to the developer to address.  It is their responsibility to update the tests alongside the features they are developing.

On top of all that, investing in actual continuous integration, as suggested by your reference model, will alleviate some of the pain of feature branches straying to far from the development branch or other feature branches.


问:
CQRS: Query write model
Context: User wants to edit entity details, say user name.

Assuming the fact that the Read Model is eventually consistent with the Write Model is it conceptually wrong to query write model in order to get the most recent state of  an entity for the page?

If I choose to query the Read Model (typical implementation according to CQRS Journey Book) how can I deal with optimistic concurrency?

Thank you in advance!

答:
Conceptually wrong? I'd say: "Yes!"

Looks like you're willing to do CRUD. Nothing intrinsically wrong with that. But it's conceptually not CQRS.

If you just need CRUD to solve your problem, just use CRUD.

Title: CQRS: Query write model


答:
Dealing with COM onjects is almost the canonical reason for setting Option Strict to off, or using the C# equivalent dynamic.

Late binding means that you loose the help of the compiler in getting things right, if you are fighting the compiler more than it is helping you, it is quite reasonable to just say "I know what I am doing".

I would recommend isolating these functions into a seperate file, and leave option strict on for everything else.

Title: When to turn off Option Strict? Or how to deal with inheritance of COM using Option Strict?

Body:
I'm trying develop an add-in for an application using it's API and I have Option Strict turned on.  Trying to work with these COM objects is causing multiple compile issues saying

Option Strict On disallows implicit conversions from 'typeA' to
  'typeB'.

I'm currently overcoming the issue by using DirectCast, which means I have to define the type in multiple places, which makes future code maintenance kind of sucky.

A simple example is:

Dim templateMgr As IEdmTemplateMgr5 = TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr)
```

<p>The CreateUtility method returns an object which implements the interface specified by the argument (argument is an EdmUtility Enum value). </p>

<p>The return is specified at compile time as <code>System.Object</code> so must be cast to the right type in order to use it. </p>

<p>With option strict on I cannot do this implicitly, so I have been using <code>DirectCast</code> thusly:</p>

<pre class="lang-vb prettyprint-override"><code>Dim templateMgr As IEdmTemplateMgr5 = DirectCast(TheVault.CreateUtility(EdmUtility.EdmUtil_TemplateMgr), IEdmTemplateMgr5)
</code>```

There are many, many, many (that many!) COM members that use generic members that make the compiler very unhappy with Option Strict turned on.

I don't particularly like using DirectCast() because it means declaring the type in multiple places scattered all throughout the code.

Is this a case where it's better to just turn off Option Strict??

I feel like there has to be a better way!

EDIT 1

My compile options are:

Option Explicit = ON

Option Strict = ON

Option Infer = ON

Option Compare = Text

Target CPU = AnyCPU

EDIT 2

Here is another example that isn't just creating a new object instance.  In this example I am using a loop to get information on all the objects in an array that returned by another function.

The return from Data.Get is always type System.Object which again causes teh compiler to complain that implicit conversion from type 'Object' to type 'String' is not allowed with Option Strict on.

Dim DataReturn As System.Array
Dim refreshFlag As Long
Try
    refreshFlag = TheTemplate.RunEx(TheCommand.mlParentWnd, TheVault.RootFolderID, DataReturn)

    If Not DataReturn.IsAllocated Then Throw New Exception("Nothing was created by the template.")

    'Refresh the folder view if required
    If refreshFlag = EdmRefreshFlag.EdmRefresh_FileList Then TheVault.RefreshFolder(TheVault.RootFolderPath)

    'Return the path(s) of the newly created file(s)
    Dim path As String = String.Empty
    For Each data As EdmData In DataReturn
        Select Case data.Type
            Case EdmDataType.EdmData_File
                path = DirectCast(data.Get(EdmDataPropertyType.EdmProp_Path), System.String)
                If path.Length > 0 Then CreatedFilesPaths.Add(path)
                path = String.Empty
        End Select
    Next
```


问:
Inheritance gone wrong
I have some code where a good inheritance model has gone downhill and I am trying to understand why and how to fix it. Basically, imagine you have a Zoo hierarchy with:

```<code>class Animal
class Parrot : Animal
class Elephant : Animal
class Cow : Animal
</code>```

etc.

You have your eat(), run(), etc methods and all is good. Then one day someone comes along and says - our CageBuilder class works great and uses the animal.weight() and animal.height(), except for the new African Bison which is too strong and can shatter the wall, so I am gonna add one more property to the Animal class -- isAfricanBizon() and use that when choosing the material and only override it for the AfricanBizon class. Next person comes and does something similar and next thing you know you have all these properties specific for some subset of the hierarchy into the base class.

What's a good way to improve/refactor such code? One alternative here would be to just use dynamic_casts to check for the types but that clutters the callers and adds a bunch of if-then-else all over the place. You can have more specific interfaces here but if all you have is the base class reference that doesnt help much either. Any other suggestions? Examples?

Thanks!

答:
Why not do something like this

class Animals { /***/ }
 class HeavyAnimals{} : Animals //The basic class for animals like the African Bison

With the class HeavyAnimals you can create the African Bison class by extending
the HeavyAnimals class.

So now you the parent class (the Animals) which can be use to create other base class like the HeavyAnimal class with can be use to create the African Bison class and other Heavy Animals. So with the African Bison you now have access to the Animal class methods and property (this is the base for all animals) and access to the HeavyAnimals class (this is the base for Heavy Animals)

Title: Inheritance gone wrong


问:
Moving methods to a MasterClass so it can be overridden, is there a better way?
I'm looking at a very large object within the application I'm working on, which is there to basically hold all the data together at a large level. Recently, we have started moving some methods out of other objects on the ModelData to the ModelData itself, because these methods are changing drastically now that we are implementing the ExistingModelData (refer to code below if you haven't already).

```<code>public RemoveStuffAction //Called from View
{
    public void doWork(HttpServletRequest request, HttpServletResponse response)
    {
        SessionData sessionData = WebUtils.getSessionData(request);
        //We actually use contracts here for validation and such
        //Passes contract to a service - ultimately resulting in..
        ModelData modelData = sessionData.getModelData();
        modelData.removeStuff(request.getParameter("stuffID"));
        //other cleanup

        //the old Code
        //ModelData modelData = sessionData.getModelData();
        //modelData.getStuffManager().removeStuff(stuffID);
        //other cleanup

        //save of model..
        //forward mapping..
        //exception handling..
    }
}

public abstract ModelData
{
    //lots of stuff

    //Methods to modify the stuff
    public void removeStuff(String stuffID) //example
    {
        this.getStuffManager().removeTheStuffFromHere(stuffID);
    }
}

public NewModelData extends ModelData
{
    //not much stuff
}

public DuplicateModelData extends ModelData
{
    //not much stuff
}

public ExistingModelData extends ModelData
{
    //quite a bit of stuff
    //Overrides many methods to modify the stuff
    public void removeStuff(String stuffID) //example
    {
        //we need the data there because we need to know what used to be there,
            //even though it is supposed to now be removed
        //what determines whether we need to know what was there or not is determined by
            //whether this is ExistingData or not.
        this.getStuffManager().getStuff(stuffID).markAsRemoved();
    }
}
</code>```

Basically, instead of creating overriding classes for all the Objects that could be changed on the model and implementing new Remove methods (and then worrying about all the times we also Add those objects so we add the correct one in each of those spots) we are moving these methods to the ModelData class and letting that one overridden class handle the removal of our Objects through inheritance.

What we have works fine, and its pretty clear to everyone on the team whats going on. I also feel with the JavaDoc we've got on ModelData that things are explained pretty well, but it just starts to bother me that we are moving so many methods to these classes - making already large classes even larger in terms of amount of text.

I've considered creating two new objects just to hold all these methods, and place the original version on the ModelData and an overridden version on the ExistingModelData, but I don't do it because I feel like it doesn't actually accomplish anything - it just shortens the amount of code in that particular class, which only makes my OCD feel a little better - and then I'll have to add an extra method call everywhere we need to use the methods in the new objects.

I also recognize that I could be too close to the situation right now and might be missing something obvious.

Is there something I could do which makes more sense and creates a cleaner design?

答:
Given that the removal is handled in generally the same way, there is really nothing wrong with this approach of having a default handling in the parent  class and overridden implementations where required. Adding other intermediary objects does not solve the fact that you have some common operations that are applicable across a range of classes.

If you are concerned about having large classes where a lot of minimally functions are dumped, consider making the ModelData class a facade that contains a number of other classes that implement specific types of operations. I have used this approach when creating service processing ecosystems where a large number of operations are available that have been similarly structured.


问:
Copyright issues with encryption algorythms
I'm developing an application for Android/Java. This application is a kind of password manager, so I'm storing encrypted passwords under the hood of a master password. There are a number of encryption algorythms DES/AES/BlowFish/TwoFish and so on. My intention is to develop application which is free of commercial copyright issues. So the questions are:

If I use built-in Java encryption API's (e.g. DES/AES)- does it mean that I will be free from possible commercial interests of DES/AES alike copyright holders?

Encryption algorythms sometimes are export limited, keeping in mind that I'm from Moscow/Russia - are there any implications of that fact?

Any other thoughts would be helpful.

答:
IMO, you will be free, it is platform owner pain to resolve those issues. However GOST algorithm is not free.

As far as i know, you must licence your business in FSB if you want to work with encryption as company, dunno if it applies to individuals. GOST algorithm is export limited. But Others, you have mentioned, are not.

Anyway I'd suggest to ask good lawyer about those issues, because i haven't tracked last changes in this field.


问:
Class member access on instantiation without variable
With a new feature in PHP 5.4, we can access a class member on the same line as instantiating the class.

e.g.

```<code>// Instead of
$obj = new myClass();
$obj->myMethod();

// PHP 5.4 allows
$obj = (new myclass())->myMethod();
</code>```

I have a class which doesn't need the object (variable) from the instantiated class, because the class being instantiated is an exit controller and just "does some things" then halts the entire system.

I'd like to know if accessing a class member at the time of instantiating the class is ok without using the variable.

```<code>// With variable (standard practice)
$obj = (new myclass())->myMethod();

// Without using the variable
(new myclass())->myMethod();
</code>```

Both code options work perfectly fine, but I've not seen this done without using the variable to store the object. And sometimes something can be done incorrectly from a technical or "best practise" standpoint but still work because of some unrelated reason (or luck etc).

So I would like to know if this is acceptable usage?

Or are there any "technical" reasons it shouldn't be done like this?

答:
It should be absolutely fine. You simply are not assigning the object to any variable and gets disposed of automatically.

BUT, I would look at larger scope issues here:

If you don't need an object, class(or method I guess in PHP) should be static instead.

```<code>// Static invocation
myClass::myMethod();
</code>```

Body:
It should be absolutely fine. You simply are not assigning the object to any variable and gets disposed of automatically.

BUT, I would look at larger scope issues here:

If you don't need an object, class(or method I guess in PHP) should be static instead.

// Static invocation
myClass::myMethod();


问:
What is the meaning of "doesn't compose"?
I see a lot of texts, especially functional programming texts, claim that certain CS concepts "don't compose". Examples are: locks don't compose, monads don't compose.

I've been having a hard time tracking down exactly the meaning of this phrase. When I think of composition, I think of either function composition or object aggregation (as in "favor composition over inheritance"), but that doesn't seem to be the sense in which people are using it here.

Can someone explain what this phrase means when used in expressions like the two examples above (that is, locks and monads)?

答:
Composability means that you can easily and reliably combine program components together to produce larger components and more complex functionality.

Some things that help make components more composable:

Idempotence. An idempotent function will always produce the same output or side effects, if called multiple times with the same parameter values.  This improves composability because the result of a function call is predictable.

Referential Transparency.  A referentially-transparent expression will always evaluate to the same result.  This improves composability by allowing identical expressions to be substituted for each other, and by allowing expressions to be calculated independently of each other (i.e. on different threads) without using locks.

Immutability. An immutable object's state cannot be changed once it is created.  This improves composability because you can rely on a stable value of the object, without worrying if some function or object somewhere has changed the state of the object after it was created.

Purity. Pure functions do not have side effects.  They only have an input and an output, which makes them more composable because you can put the output of one function into the input of another function without worrying about whether or not something outside of the function has changed.

Locks don't compose because they are an outside element which you must rely on when combining two operations together that share some state, and for all sorts of reasons which have to do with the complexity inherent in using locks.

The phrase "monads don't compose" doesn't make much sense to me.  The whole point of a monad is to take some stateful thing like keyboard input or screen output, and turn it into a purer, mathematical form that is, in fact, more composable.


问:
Precedence of function in Shunting-yard algorithm
I am working through the Shunting-yard algorithm, as described by wikipedia.

The description of the algorithm when dealing with operators is as follows:

If the token is an operator, o1, then:

while there is an operator token, o2, at the top of the operator
  stack, and either

```<code>o1 is left-associative and its precedence is less than or equal to
that of o2, or

o1 is right associative, and has precedence less than that of o2,
</code>```

then pop o2 off the operator stack, onto the output queue;

push o1 onto the operator stack.

However, they give the following example:

Input: sin max 2 3 / 3 * 3.1415

When the algorithm hits the / token, the description of what should happen is as follows:

```<code>Token |        Action       |   Output (in RPN) |   Operator Stack
...
/     | Pop token to output | 2 3 max           | / sin
...
</code>```

They are popping the function token max off the stack and putting into the queue. According to their algorithm, this would seem to mean the function token is both an operator, and has a precedence less than that of  the / operator.

There is no explanation as to whether or not this is the case. So, for the Shunting-yard algorithm, what is the precedence of a function? Are functions right or left associative? Or is wikipedia just incomplete/inaccurate?

答:
I believe the direct answer is simply that functions are not operators. From the page you linked:

If the token is a function token, then push it onto the stack.

This is all it needs to say, since the function case (prefix to postfix) is much simpler than the operator case (infix to postfix).

For the follow-up questions: The notions of precedence and associativity are only needed because of the inherit ambiguity in any expression with multiple infix operators. Function tokens are already using prefix notation, so they simply don't have that problem. You don't need to know whether sin or max has "higher precedence" to figure out that max needs to be evaluated first; it's already clear from the order of the tokens. That's why computers prefer pre/postfix notation to begin with, and why we have this algorithm for converting infix to pre/postfix.

You do need to have some kind of rule for where a function's arguments start and end when no parenthesis are present, so you could say that functions "take precedence" over operators or vice versa. But unlike infix operators, a single consistent rule for all functions is enough to make their compositions completely unambiguous.


问:
Refactoring techniques for asp.net webforms application
I'm working on a large application written in asp.net web forms. It was developed under asp.net 1.0, and still uses DataGrid, though portions have been updated.

Most of the code resides in either the codebehind, or in controller classes that can't be instantiated outside of a running IIS. (The controller framework we use provides lifetime management tied to session state.) Data access is through a custom DAL, meaning that most of that code also requires a live database with proper data inside it.

I want to decouple the code from the database and the web server, so that I can run it under a test harness. Are there any good strategies for moving from this sort of code to a more testable structure?

答:
The problem is. that with the information you give, the range of possible answers is theoretically infinite.

If I collect the hard facts I get the following picture:

ASP.NET 1.0 Webform

DataGrid

Tight coupling

Dataaccess via custom DAL

Besides that, you didn't say in which direction your refactoring is heading.
Simply »cleaning the mess« is a good starting point, but not enough. And as @Wayne poined out: it would end up effectively in a rewrite.

There are at least 2 possibilities:

1) Making a SPA where you have a smart frontend and do most - or at least a good deal - of logic in the frontend

2) Making a conventional web application with WebAPI.
Besides, though I actually have not worked with it, but perhaps it is worth a glimpse: NancyFX

Depending on how big your application / codebase is - and on how hip you want to be, you should think about using microservices

Some easy recommendations are:

Replacing the Datagrid with a JS-equivalent: datatables.net or jqGrid

Data access is through a custom DAL, meaning that most of that code also requires a live database with proper data inside it.

This could be mocked or stubbed away

For the rest, it depends:

If the codebase is somehow in shape. Try to guess, what the code does. Write a test. See if your assumption holds. If so, write another test, to veriy another assumption. If the PITA-factor is too high, rewrite the business logic completely. Otherwise repeat and build an iterative refined understanding of the code and evolve a finegrained test suite. Step by step you are knitting a saftey net around the code. If it is tight enough, take the chainsaw and cut the code in handy pieces.

I have to admit, that this is a very general advice, but without further knowledge of your codebase, it is hard to give any concrete advice.


答:
Should unit tests run on every git branch?

This one is an easy one.
The main point of doing continuous integration is to detect errors as early as possible in the build process.

From this it should be clear, that you should

a) run a testsuite on every branch of your code

b) do not allow checking in code, which neither runs nor passes all tests

This is the minimum requirement for checking in code and doing successful continous integration

tl;dr

yes

Offtopic:

I read the other day an interesting article published on a well known german IT-Portal (Heise.de) from a well known german consutant Eberhard Wolff about branches as a contradiction to continous integration in which he argued, that developing branches is in principle a violation of CI, since you separate code for some time and detect conflicts only when merging branches back in. Branches could only be tested in isolation - which is obvious, because of their nature. He votes for one main branch and feature toggles for disabling new features on production. Of course this is not always a feasible solution (he clearly sees that toggles are not without a cost). Sometimes branches are an alternative. But he recommends really shortlived branches.

Here is the (german) article.

Body:
I am new to repo management / continuous integration.

I designed a repo in the following way

```<code>PROJ
 |-src
 |-include
 |-lib
 |-config
PROJ_Unit_Tests
 |-src
 |-config
PROJ_Doc
</code>```

When I now do continuous integration, i.e., running unit test on the build server, should they run on every branch or only on the develop branch?

If they only run on the develop branch and a feature branch going on for long, I am afraid that the developer is pushing changes to his feature branch which would actually fail the build. On the other hand, if a feature branch deactivates functionality of the develop branch, then the programmer has to manually disable to corresponding unit tests.


Title: What is the meaning of "doesn't compose"?

Body:
I see a lot of texts, especially functional programming texts, claim that certain CS concepts "don't compose". Examples are: locks don't compose, monads don't compose.

I've been having a hard time tracking down exactly the meaning of this phrase. When I think of composition, I think of either function composition or object aggregation (as in "favor composition over inheritance"), but that doesn't seem to be the sense in which people are using it here.

Can someone explain what this phrase means when used in expressions like the two examples above (that is, locks and monads)?

Body:
When people say "X doesn't compose", what they mean by "compose" really just means "put together", and what and how you put them together can be very different, depending on what exactly "X" is.

Also, when they say "doesn't compose", they can mean some slightly different things:

You can't put two Xs together at all, period.

You can put two Xs together, but the result might not be an X (IOW: X is not closed under composition.)

You can put two Xs together, but the resulting X might not work the way you expect it to.

An example for #1 is parsers with scanners/lexers. You might hear the phrase "scanners/lexers don't compose". That's not actually true. What they mean is "parser which use a separate lexing stage do not compose".

Why would you want to compose parsers? Well, imagine you are an IDE vendor like JetBrains, the Eclipse Foundation, Microsoft, or Embarcadero, and you want to build an IDE for a web framework. In typical web development, we often mix languages. You have HTML files with <script> elements containing ECMAScript and <style> elements containing CSS. You have template files containing HTML, some programming language, and some template language metasyntax. You don't want to write different syntax highlighters for "Python", "Python embedded in a template", "CSS", "CSS within HTML", "ECMASCript", "ECMAScript within HTML", "HTML", "HTML within a template", and so on and so forth. You want to write a syntax highlighter for Python, one for HTML, one for the template language, and then compose the three into a syntax highlighter for a template file.

However, a lexer parses the entire file into a stream of tokens, which only makes sense for that one language. The parser for the other language can't work with the tokens the lexer passes it. For example, Python parsers are typically written in such a way that the lexer keeps track of indentation and injects fake INDENT and DEDENT tokens into the token stream, thus allowing the parser to be context-free even though Python's syntax actually isn't. An HTML lexer however will completely ignore whitespace, since it has no meaning in HTML.

A scannerless parser, however, which simply reads characters, can pass the character stream off to a different parser, which can then hand it back, thus making them much easier to compose.

An example for #2 is strings with SQL queries in them. You can have two strings, each of which has a syntactically correct SQL query in it, but if you concatenate the two strings, the result may not be a syntactically correct SQL query. That's why we have query algebras like ARel, which do compose.

Locks are an example of #3. If you have two programs with locks, and you combine them into a single program, you still have a program with locks, but even if the two original programs were completely correct, free of deadlocks and races, the resulting program does not necessarily have this property. Correct usage of locks is a global property of the entire program, and a property that is not preserved when you compose programs. This is different from, for example, transactions, which do compose. A program which correctly uses transactions can be composed with another such program and will yield a combined program which correctly uses transactions.


问:
Should the story points of stories created after splitting a story add up to the number of story points of that story?
Suppose I have a user story of size 20 that can be split in other 2 user stories, making the original story an epic. Should the sum of these user stories add up to 20? What's the best practice in this case? If they don't add up that could mean in practical terms that the overall complexity of the project changed.</p>

答:
No. The new numbers should not be compared to the old number. That's not thinking of story points the right way.

For example, if I were to split up an 8 point story into 1 point stories, I might get to 15 to 25 1 point stories. Is this because my team's definition of 1 point or 8 points is wrong? No, we defined 1 point to be a story which could be done in a few of hours, whereas we defined 8 points to be the largest size a single developer could push through in a two week sprint.

Other teams may end up defining story points differently, but idea is to use numbers that represent an honest estimate according to the team's rules and not lying in planning to make the maths work.


问:
Do we need to validate entire module usage or just arguments of public methods?
I've heard that it is recommended to validate arguments of public methods:

Should one check for null if he does not expect null?

Should a method validate its parameters?

MSDN - CA1062: Validate arguments of public methods (I have .NET background but question is not C# specific)

Motivation is understandable. If a module will be used in a wrong way, we want to throw exception immediately instead of any unpredictable behavior.

What bothers me, is that wrong arguments is not the only error which can be made while using a module. Here's some error scenarios where we need to add checking logic if we follow recommendations and don't want error escalation:

Incoming call - unexpected arguments

Incoming call - module is in a wrong state

External call - unexpected results returned

External call - unexpected side-effects (double-entry to a calling
module, breaking other dependencies states)

I've tried to take into account all these conditions and write a simple module with one method (sorry, not-C# guys):

```<code>public sealed class Room
{
    private readonly IDoorFactory _doorFactory;
    private bool _entered;
    private IDoor _door;
    public Room(IDoorFactory doorFactory)
    {
        if (doorFactory == null)
            throw new ArgumentNullException("doorFactory");
        _doorFactory = doorFactory;
    }
    public void Open()
    {
        if (_door != null)
            throw new InvalidOperationException("Room is already opened");
        if (_entered)
            throw new InvalidOperationException("Double entry is not allowed");
        _entered = true;
        _door = _doorFactory.Create();
        if (_door == null)
            throw new IncompatibleDependencyException("doorFactory");
        _door.Open();
        _entered = false;
    }
}
</code>```

Now It's safe =)

It's quite creepy. But imagine how creepy it can be in a real module with dozens of methods, complex state and a lot of external calls (hi, dependency injection lovers!). Note that if you're calling a module which behavior can be overridden (non-sealed class in C#) then you're making an external call and consequences are not predictable at the scope of the caller.

Summing up, what is the right way and why? If you can choose from options below, answer additional questions, please.

Check entire module usage. Do we need unit tests? Is there examples of such code? Should dependency injection be limited in usage (since it will cause more checking logic)? Isn't it practical to move those checks to debug-time (do not include in release)?

Check only arguments. From my experience, argument checking - especially null checking - is the least effective check, because argument error rarely lead to complex mistakes and error escalations. Most of the time you'll get a NullReferenceException at the next line. So why argument checks are so special?

Don't check module usage. It's quite unpopular opinion, can you explain why?

答:
A class is responsible for its own state. So validate to the extent that it keeps or puts things in an acceptable state.

If a module will be used in a wrong way, we want to throw exception immediately instead of any unpredictable behavior.

No, don't throw an exception, instead deliver predictable behavior. Corollary to state responsibility is to make the class/application as tolerant as practical. For example, passing null to aCollection.Add()? Just don't add and keep going. You get null input for creating an object? Create a null object or a default object. Above, the door is already open? So what, keep going. DoorFactory argument is null? Create a new one. When I create an enum I always have a Undefined member. I make liberal use of Dictionarys and enums to define things explicitly; and this goes a long way toward delivering predictable behavior.

(hi, dependency injection lovers!)

Yea though I walk through the shadow of the valley of parameters I will fear no arguments. To the preceding I also use default and optional parameters as much as possible.

All the above allows internal processing to keep going. In a particular application I have dozens of methods across multiple classes with only a single place where an exception is thrown. Even then, it's not because of null arguments or that I could not continue processing it's because the code ended up creating a "non functional"/"null" object.

edit

quoting my comment in it's entirety. I think the design should not simply "give up" when encountering 'null'. Especially using a composite object.

We're forgetting key concepts/assumptions here - encapsulation & single responsibility. There is virtually no null checking after the first, client-interacting layer. The code is tolerant robust. Classes are designed with default states and so work without being written as if interacting code is bug-ridden, rogue junk. A composite parent does not have to reach down the child layers to evaluate validity (and by implication, check for null in all the nooks and crannies). The parent knows what a child's default state means

end edit


答: IMO, algorithms are not copyrighted, libraries are. But if you are using something that comes by default from JAVA, then there will not be any copyrighted issues. </p>

Title: Copyright issues with encryption algorythms

Body:
I'm developing an application for Android/Java. This application is a kind of password manager, so I'm storing encrypted passwords under the hood of a master password. There are a number of encryption algorythms DES/AES/BlowFish/TwoFish and so on. My intention is to develop application which is free of commercial copyright issues. So the questions are:

If I use built-in Java encryption API's (e.g. DES/AES)- does it mean that I will be free from possible commercial interests of DES/AES alike copyright holders?

Encryption algorythms sometimes are export limited, keeping in mind that I'm from Moscow/Russia - are there any implications of that fact?

Any other thoughts would be helpful.


问:
When speaking, how can I say that the time complexity order of an algorithm is O(N log N)?
What term can I use to describe something with O(N log N) complexity?

For example:

O(1): Constant

O(log N): Logarithmic

O(N): Linear

O(N log N): ??????

O(N2): Quadratic

O(N3): Cubic

答: "N log N" is as good as you're going to get, and should be well understood by professional programmers. You can't expect there to be a single word to describe every complexity class that exists.</p>


答: It is sometimes called "loglinear", although that word actually means something different. I would just stick with "N log N", though, as @Philip's answer suggests.</p>

Title: When speaking, how can I say that the time complexity order of an algorithm is O(N log N)?

Body:
What term can I use to describe something with O(N log N) complexity?

For example:

O(1): Constant

O(log N): Logarithmic

O(N): Linear

O(N log N): ??????

O(N2): Quadratic

O(N3): Cubic


答: Not necessarily.  The reason that higher possible story point estimates are usually farther apart (like in the Fibonacci sequence) is that estimation is less accurate, so it's not worth distinguishing between e.g. a 13 and a 14.  But after analysis to split the stories, each part can be estimated with higher accuracy (that's one of the main advantages of smaller stories).  So the total number can be different, because it should be more accurate.</p>

Title: Should the story points of stories created after splitting a story add up to the number of story points of that story?

Body: Suppose I have a user story of size 20 that can be split in other 2 user stories, making the original story an epic. Should the sum of these user stories add up to 20? What's the best practice in this case? If they don't add up that could mean in practical terms that the overall complexity of the project changed.</p>


答:
No.  When you break up a task into subtasks there will be now be additional:

time to context switch between each piece

time to record each small story in the issue tracking system

setup / teardown of configuration and test data

Also

if you using the fibonnaci series (or basically anything other than every number), then breaking down a 13 point story (that was more like 11 but assigned 13 as the closest numeber might result in 3 stores, 3+5+3 = 11 points or a different 13 point story that is actually more like a 16 point story but assigned as a 13 point one 'cos 13 was closer to 16 than 21 was, might break down to 8+5+3 = 16(this is not even allowing dor startup , context switches, etc).  So one 13 point story became 11 subpoints and another 13 point story became 16 subpoints.

Finally, this sort of focus on points at a small scale is frequently unproducitve and often gets used to try and estimate a points = man hours ratio.

I recommend using points to discuss relative sizing and generate discussion during grooming.  Only use them retroactively over relatively long periods, i.e. months, when you need to forecast.  Even them it doesn't work well as teams change and so does knowledge over time.  Today's 11 pointer may be a 5 pointer with the staff and knowledge available then or vice versa.


问:
HashMap to replace Singletons?
Consider the following: I have controllers and views in a client-application. As this runs purely on the client side, each controller must only exist once.

At first I thought about implementing everything as Singletons but this doesn't really feel right for a few reasons.

A few is instantiated like so:

```<code>abstract class View(controller: Controller)
</code>```

now in each view I do certain things, based on the controller I got.

Some controllers need to have parameters set upon initialization, this speaks for a class, rather than a singleton. (Of course I could do: MyObject.set(whatever) but that's neither clean nor nice)

Now my idea was to create a simple mutable HashMap for the controllers and store the classes as keys and exactly one corresponding object as a value.

Now upon each initialization I just check the HashMap for an instance and if there is one already, I return that instead.

Seems hacky though.

Of course I could just stick with classes all the way, but I'm not sure if this is a good way. I mean, if I instantiate new Controllers every few seconds ... (It's a game we're talking about, so there is already a lot of calculations going on)

答:
At a high level, you're essentially asking:

Is building a Controller cache better than using singletons?

I would argue that in your situation, yes, it is.  And here's why.

From your description it doesn't sound like you need the semantics of a singleton here.  Your game would be just fine if you instantiated a new Controller every time one was needed.

In other words, your requirement isn't:  All references to a Controller must resolve to a single unique Controller state."

Instead, your requirement seems to be:  When retrieving a Controller instance, it should be fast.

That is an argument for using a cache.  Not singletons.

If you want to implement that cache using a HashMap then go for it :)

Title: HashMap to replace Singletons?


答:
There is a jargon term linearithmic meaning exactly this.

I don't believe that it's universally understood by all programmers, so if you're not careful then it will obscure more than it informs. Personally I don't normally use it, and if I did then I'd probably define it on first use, for example "this article considers linearithmic (O(N log N)) algorithms".


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
Because for most languages, most compiler/runtime messages don't make any sense.  (C++ and Java especially, I am looking at you!)  Getting the errors right tends to be rather low on a language designer's list of priorities.  Getting things that work right to work right is usually a bigger priority, and a lot of time they don't bother with polishing the little details.

That's one of the reasons why I enjoy working in Delphi.  The entire language is full of attention to the little details, including the errors.  Compiler messages make sense.  Runtime error messages make sense.  Stack traces make sense.  It's one of the things that makes it, by far, the easiest language to debug that I've ever worked with.


问:
What is the time complexity of the algorithm to check if a number is prime?
What is the time complexity of the algorithm to check if a number is  prime?

This is the algorithm :

bool isPrime (int number) {
    if (number < 2) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    for (int i=3; (i*i) <= number; i+=2) {
        if (number % i == 0 ) return false;
    }
    return true;
}
```

答:
The maximum execution time of this algorithm is O (sqrt (n)), which will be achieved if n is prime or the product of two large prime numbers. </p>

<p>Average execution time is tricky; I'd say something like O (sqrt (n) / log n), because there are not that many numbers with only large prime factors. </p>

Body:
The maximum execution time of this algorithm is O (sqrt (n)), which will be achieved if n is prime or the product of two large prime numbers.

Average execution time is tricky; I'd say something like O (sqrt (n) / log n), because there are not that many numbers with only large prime factors.


答: Because the factor log n grows slowly, a qualitative description for O(n log n) would be "almost linear".  Depending on your audience the class of O(n log n) algorithms might be well known, as for example this is the case with fast sorting on n items by comparisons.


问:
What is the advantage of global functions when writing functional code
I am a Swift developer and am trying to adopt a functional / reactive style in my code. I have been using ReactiveCocoa in all my projects and I have started giving RAC 3.0 a try. One thing I have seen is that in project, there is heavy use of curried functions that have a global scope (i.e. not tied to an instance).

What I am keen to understand is why global functions is a good idea?

Is this something that is unique to curried functions or is it a general functional programming attribute?

答:
At it's purest, functional programming is about defining a set of data types, devoid of behaviour, and then defining a set of "free" functions over those data types, which can be freely extended as need arises. This usually comes with some sort of namespace/module mechanism, so despite the fact that the functions are free, they're not global in the sense that there's a single namespace for everything (note: I know next to nothing about Swift, so if it doesn't have a namespacing mechanism for free functions and if they indeed fall into a global namespace, then I would say it's something to be discouraged, and find the language lacking in that regard).

Now, assuming you have namespaces, is it a good idea? I suppose it's good enough, since it works for many people (and they will usually claim it works better than the alternative). It's a good way to model things in general, and it's usually a better way to model abstract concepts that would feel forced being squeezed into OO class hierarchies. That said, it has its shortcomings as illustrated by the expression problem, where FP falls squarely on the "easy to add functions, hard to add cases" side. Not coincidentally, this means that many things that are dos in FP are dont's in OO, and vice versa.

That's why the recent hybrid OO/FP languages, Swift one of them, are set on claiming some sort of middle ground between the two. But where this middle ground is, and what's just Haskell/Java written in another language will vary on a case by case basis.


问:
Module level logger function
I've recently been assigned to a new project because I'm one of the only developers at my company who has used Python extensively in the past.  My first task was to clean up the code base and make it more Pythonic - while doing so I came across this:

```<code>import logging   # The builtin logging module

def logInfo(message):
    logger = logging.getLogger('')
    logger.info(message)

def logError():
    logger = logging.getLogger('')
    logger.error('Failed: {0}'.format(traceback.format_exc()))

def logCritical(message):
    logger = logging.getLogger('')
    logger.critical(message)

def logWarning(message):
    logger = logging.getLogger('')
    logger.warn(message)

def logDebug(message):
    logger = logging.getLogger('')
    logger.debug(message)
</code>```

This smells pretty bad to me - it seems that a much cleaner solution would be to just create a global logger object at the top of the file, and then just use the normal logger.debug|info|error|warn|critical functions.  Am I overthinking this?

Of course, then there is all of the hairiness of a global object - in which case maybe I'd do something like

```<code>@memoize
def getLogger(name='__main__'):
    return logging.getLogger(name)
</code>```

With an appropriate memoizing function.

This is a pretty young project still, so we have a lot of freedom in how we set this up.

答:
A common way is, to define one global logger at the beginning of the module with:

```<code>import logging
logger = logging.getLogger(__name__)
</code>```

so it's easier to assign different log-levels to different modules. If you don't have a distinguishing logger name, you can directly use the log-functions of logging; instead of logDebug simply write logging.debug.

Title: Module level logger function

Body:
A common way is, to define one global logger at the beginning of the module with:

import logging
logger = logging.getLogger(__name__)

so it's easier to assign different log-levels to different modules. If you don't have a distinguishing logger name, you can directly use the log-functions of logging; instead of logDebug simply write logging.debug.


问:
How to maintain an unpopulated 'config' source file in git repo?
Suppose I create some widget, and decide to share it with Github. In this widget project, there's some configuration/preferences file. I need to share what the values being set are, so that if anyone else wished their own widget they'd know what to set. But I don't necessarily want or need to share my own settings.

This would be a case in which some/all of the settings have no concept of a 'default' - they all need to be explicitly set by the programmer.

I thought I was going to find an answer in this question, but really that (or at least it's answers) are more focussed on keeping things secret. I don't need to share in confidence - I just don't need to share.

In essence, I need to deploy Foo := 'Bar', but commit/push/share Foo :=.

What's the best way of handling this in Git?

Some possible solutions:

Commit the unpopulated file; don't include in later commits with preferences set. Disadvantage: if I add a new setting later, need to remove all values to commit it, and then set them again.

Set the values by import/inclusion (as applicable for the language) to ensure an upfront (and less confusing than it might otherwise be) error; clearly state requirements in a readme. Disadvantage: noone likes errors.

Branches? I've never really had the need to use multiple, but I have a feeling the 'right' way to do this might be an un-pushed 'deploy' branch with the values set, and unset in the pushed 'master' branch; just deal with the merge conflicts as they arise on adding new properties? Maybe? Same disadvantage as (1) really, but maybe it's the better practice?

答:
My first thought is: Don't store the populated config file in git at all. Put the unpopulated file in git and on installation or first run, create the populated file in another place. If the configuration is user specific, this other place would be in:

Windows: %APPDATA%

Linux: a dot file or a dot folder in the user's home directory. Something like ~/.myapp_config

Mac OS X: the user's Library folder, probably in a subdirectory for your app.


答:
I would go with a modified version of scenario 1. Instead of adding your real configuration file to the repo, add a prototype config file. When the widget first runs, it detects if the config file is present or not. If not present, it renames the prototype file and then loads it. The prototype file can have sane default values (might no "work" but don't crash the widget).

This will allow you to have your local config file (which is never committed, but should probably be backed up) as well as a version that can be publicly pushed that doesn't contain your private information.

Title: How to maintain an unpopulated 'config' source file in git repo?

Body:
Suppose I create some widget, and decide to share it with Github. In this widget project, there's some configuration/preferences file. I need to share what the values being set are, so that if anyone else wished their own widget they'd know what to set. But I don't necessarily want or need to share my own settings.

This would be a case in which some/all of the settings have no concept of a 'default' - they all need to be explicitly set by the programmer.

I thought I was going to find an answer in this question, but really that (or at least it's answers) are more focussed on keeping things secret. I don't need to share in confidence - I just don't need to share.

In essence, I need to deploy Foo := 'Bar', but commit/push/share Foo :=.

What's the best way of handling this in Git?

Some possible solutions:

Commit the unpopulated file; don't include in later commits with preferences set. Disadvantage: if I add a new setting later, need to remove all values to commit it, and then set them again.

Set the values by import/inclusion (as applicable for the language) to ensure an upfront (and less confusing than it might otherwise be) error; clearly state requirements in a readme. Disadvantage: noone likes errors.

Branches? I've never really had the need to use multiple, but I have a feeling the 'right' way to do this might be an un-pushed 'deploy' branch with the values set, and unset in the pushed 'master' branch; just deal with the merge conflicts as they arise on adding new properties? Maybe? Same disadvantage as (1) really, but maybe it's the better practice?


答:
The bigger the story, the less accurate the estimate will be. When you're talking about a 20 point story, that could easily reduce down to four 10 point stories, or two or three five point stories. That estimate of 20 is so large as to be almost as useless as a coin toss. All 20 really means is "it's too big"; the number itself means nothing.

The whole point of splitting stories into smaller stories is to be able to do a better job estimating. Since the estimates are better when you estimate multiple smaller stories vs one big story, that means they won't necessarily be mathematically the same.

Bottom line: don't worry about it. The estimates are merely a tool to help you plan. They don't have to add up, they don't have to remain static.


问:
How do I prevent a long running SQL query from looking stuck?
If I had a method like:

```<code>private void someMethod()
{
    runSqlQueryA();
    runSqlQueryB();
    runSqlQueryC();
}
</code>```

My understanding is this method will be one thread.

In weblogic, the thread will appear stuck if it's been running for longer than 10 minutes (by default).

My question is - if these SQL queries are routinely take a long time, how do I prevent Weblogic from detecting the thread as stuck?

One option would be to simply change the stuck thread threshold, but I'm wondering if there's a better solution, such as a java thread manager that keeps it refreshed.

答:
WebLogic is mainly a web application container.  As such, anything that take minutes (more than a few seconds) to process will be suspect.  Threads flagged as stuck is an indication that something may be wrong.  If you end up with too many stuck threads, the server is likely to get in a very bad state.  Other than modifying the times or running on an un-managed (by WebLogic) thread pool there is little you can do not to have a long running thread from looking stuck.  Using your own thread pool can cause significant performance issues.

If you have processes that take this long, you may want to use JMS or some other queuing system to process them.  This will allow you to limit the number of concurrent processes running this slow process.  The queue could be processed on a separate JVM with appropriately modified stuck thread times.

If the queries can run in parallel, then it may be possible to queue multiple JMS items. These would be less likely to run long enough to appear stuck.

As designed you will get thread flagged as stuck.  This is not necessarily an issue unless you generate too many such threads, or they never complete.  It is likely worthwhile examining other options rather than a container for running the process