규칙 엔진-장단점
나는 Rules Engine 이라는 것을 사용하는 프로젝트를 감사하고 있습니다. 간단히 말해서 애플리케이션 코드에서 비즈니스 로직을 외부화하는 방법입니다.
이 개념은 나에게 완전히 새로운 것이고 나는 그것에 대해 꽤 회의적입니다. 지난 몇 년 동안 사람들이 빈혈 도메인 모델 에 대해 이야기하는 것을 듣고 규칙 엔진 접근 방식에 의문을 제기합니다. 나에게 그것들은 도메인 모델을 만드는 훌륭한 방법처럼 보입니다. 예를 들어 규칙 엔진과 상호 작용하는 자바 웹앱을 수행하고 있다고 가정 해 보겠습니다. 그런 다음 동일한 도메인을 기반으로하는 Android 앱을 사용하기로 결정했습니다. Android 앱이 Rules Engine 과도 상호 작용하는 것을 원하지 않는 한, 이미 작성된 비즈니스 로직을 놓쳐 야합니다.
아직 경험이 없기 때문에 호기심 만 있으면 규칙 엔진을 사용할 때의 장단점에 대해 듣고 싶었습니다. 제가 생각할 수있는 유일한 장점은 일부 비즈니스 규칙을 변경하기 위해 전체 애플리케이션을 다시 빌드 할 필요가 없다는 것입니다 (하지만 실제로 얼마나 많은 앱이 그렇게 많이 변경 되었습니까?). 하지만 규칙 엔진을 사용하여 문제를 해결하는 것은 마치 산탄 총에 반창고를 씌우는 것과 같은 소리입니다.
업데이트-이 글을 쓴 후 신인 Martin Fowler 는 Rules 엔진 사용에 대해 블로그에 올렸습니다 .
내가 본 대부분의 규칙 엔진은 시스템 코드에서 블랙 박스로 간주됩니다. 도메인 모델을 구축하려면 특정 비즈니스 규칙이 도메인 모델에 내재되어 있기를 원할 것입니다. 예를 들어 개체에 잘못된 값이있을 때 알려주는 비즈니스 규칙이 있습니다. 이를 통해 여러 시스템이 비즈니스 로직을 복제하지 않고도 도메인 모델을 공유 할 수 있습니다. 각 시스템이 동일한 규칙 서비스를 사용하여 내 도메인 모델을 검증하도록 할 수 있지만 이것은 내 도메인 모델을 약화시키는 것처럼 보입니다 (질문에서 지적했듯이). 왜? 항상 모든 시스템에서 비즈니스 규칙을 일관되게 적용하는 대신 시스템 프로그래머가 비즈니스 규칙을 적용해야하는시기 (규칙 서비스 호출)를 결정하기 때문입니다. 도메인 모델이 완전히 채워지면 문제가되지 않을 수 있지만 다음과 같은 경우 문제가 될 수 있습니다.
비즈니스 규칙에는 의사 결정이라는 또 다른 클래스가 있습니다. 예를 들어, 보험 회사는 신청자를 인수하는 위험을 분류하고 보험료를 받아야 할 수 있습니다. 이러한 유형의 비즈니스 규칙을 도메인 모델에 배치 할 수 있지만 이와 같은 시나리오에 대한 중앙 집중식 결정이 일반적으로 바람직하며 실제로 서비스 지향 아키텍처에 매우 적합합니다. 이것은 왜 시스템 코드가 아닌 규칙 엔진인지에 대한 질문을 던집니다. 규칙 엔진이 더 나은 선택이 될 수있는 곳은 의사 결정을 담당하는 비즈니스 규칙이 시간이 지남에 따라 변경되는 곳입니다 (다른 답변에서 지적했듯이).
규칙 엔진을 사용하면 일반적으로 시스템을 다시 시작하거나 새 실행 코드를 배포하지 않고도 규칙을 변경할 수 있습니다 (공급 업체로부터받은 약속에 관계없이 규칙 엔진에 결함이없는 경우에도 비 프로덕션 환경에서 변경 사항을 테스트해야합니다). , 인간은 여전히 규칙을 변경하고 있습니다.) "데이터베이스를 사용하여 변경되는 값을 저장함으로써 그렇게 할 수 있습니다"라고 생각하신다면 맞습니다. 규칙 엔진은 새로운 일을하는 마법의 상자가 아닙니다. 더 높은 수준의 추상화를 제공하는 도구로, 휠을 재발 명하는 데 덜 집중할 수 있습니다. 많은 공급 업체는 비즈니스 사용자가 규칙 언어를 배우는 대신 공백을 채울 수 있도록 템플릿을 만들 수 있도록하여이를 한 단계 더 발전시킵니다.
템플릿에 대한 한 가지주의 사항 : 템플릿은 최소한 규칙을 설명해야하므로 템플릿없이 규칙을 작성하는 것보다 시간이 적게 걸리지 않습니다. 더 높은 초기 비용에 대한 계획 (시스템 코드에 직접 규칙을 작성하는 것과 비교하여 변경되는 값을 저장하기 위해 데이터베이스를 사용하는 시스템을 구축하는 것과 동일)-ROI는 시스템 코드의 향후 유지 관리 비용을 절약하기 때문입니다. .
빈혈 도메인 모델에 대한 귀하의 우려는 타당하다고 생각합니다.
저는 제가 일하는 프로덕션에서 실행되는 잘 알려진 상용 Rete 규칙 엔진의 두 가지 응용 프로그램을 보았습니다. 하나는 성공이고 다른 하나는 실패라고 생각합니다.
성공적인 애플리케이션은 각각 ~ 30 개의 분기점으로 구성된 ~ 10 개의 트리로 구성된 의사 결정 트리 앱입니다. 규칙 엔진에는 비즈니스 직원이 규칙을 유지할 수있는 UI가 있습니다.
덜 성공적인 응용 프로그램은 규칙 데이터베이스에 ~ 3000 개의 규칙이 있습니다. 새 규칙이 추가 될 때 충돌하는 규칙이 있는지 아무도 모릅니다. Rete 알고리즘에 대한 이해가 거의없고 제품에 대한 전문 지식이 회사를 떠났으므로 손댈 수없고 리팩터링 할 수없는 블랙 박스가되었습니다. 배포주기는 여전히 규칙 변경의 영향을받습니다. 규칙이 변경되면 완전한 회귀 테스트를 수행해야합니다. 기억도 문제였습니다.
나는 가볍게 밟았다. 규칙 세트의 크기가 적당한 경우 위에 제공된 단순한 전자 메일 샘플과 같이 변경 사항을 이해하기 쉽습니다. 규칙의 수가 수백 개에 이르면 문제가있을 수 있다고 생각합니다.
또한 애플리케이션에서 단일 병목 현상이되는 규칙 엔진에 대해 걱정합니다.
엔진 공간을 규칙적으로 분할하는 방법으로 객체를 사용하는 데 아무런 문제가 없다고 생각합니다. 개인 규칙 엔진을 연기하는 개체에 동작을 포함하는 것은 괜찮은 것 같습니다. 규칙 엔진이 개체의 일부가 아닌 상태가 제대로 실행되도록 요구할 때 문제가 발생합니다. 그러나 그것은 디자인이 어려운 또 다른 예일뿐입니다.
규칙 엔진은 특정 경우에 많은 가치를 제공 할 수 있습니다.
첫째, 많은 규칙 엔진이보다 선언적인 방식으로 작동합니다. 매우 조잡한 예는 코드 블록에 정규식을 할당 할 수있는 AWK입니다. 정규식이 파일 스캐너에 표시되면 코드 블록이 실행됩니다.
이 경우 큰 AWK 파일이 있고 Yet Another "규칙"을 추가하려는 경우 파일 맨 아래로 쉽게 이동하여 정규식과 논리를 추가하고 다음을 수행 할 수 있음을 알 수 있습니다. 그것. 특히 많은 응용 프로그램의 경우 다른 규칙이 수행하는 작업에 특별히 관심이 없으며 규칙이 실제로 서로 상호 운용되지 않습니다.
따라서 AWK 파일은 "규칙 수프"처럼됩니다. 이러한 "규칙 수프"특성 덕분에 사람들은 시스템에있을 수있는 다른 모든 규칙에 대해 거의 관심없이 자신의 도메인에 매우 집중할 수 있습니다.
예를 들어 Frank는 총 $ 1000 이상의 주문에 관심이 있으므로 관심있는 규칙 시스템에 입력합니다. "주문 총계> 1000 THEN 이메일 Frank".
한편 Sally는 "IF order.source == 'WEST_COAST'THEN 이메일 Sally"라는 서부 해안의 모든 주문을 원합니다.
따라서이 사소하고 인위적인 경우에서 주문이 두 규칙을 모두 충족 할 수 있지만 두 규칙은 서로 독립적이라는 것을 알 수 있습니다. 서해안에서 $ 1200 주문을 받으면 Frank와 Sally에게 알립니다. Frank가 더 이상 염려하지 않을 때 그는 단순히 수프에서 자신의 규칙을 제거합니다.
많은 상황에서 이러한 유연성은 매우 강력 할 수 있습니다. 이 경우와 마찬가지로 간단한 규칙을 위해 최종 사용자에게 노출 될 수도 있습니다. 높은 수준의 식과 가벼운 스크립팅을 사용합니다.
이제 분명히 복잡한 시스템에는 발생할 수있는 모든 종류의 상호 관계가 있습니다. 이것이 전체 시스템이 "규칙으로 완료"되지 않는 이유입니다. 누군가, 어딘가에서 손을 떼지 않는 규칙을 담당 할 것입니다. 그러나 그것이 반드시 그러한 시스템이 제공 할 수있는 가치를 감소시키는 것은 아닙니다.
이것은 규칙이 생성 할 수있는 데이터에 대해 규칙이 실행되는 전문가 시스템과 같은 것에도 적용되지 않지만 더 간단한 규칙 시스템에 적용됩니다.
어쨌든이 예제가 규칙 시스템이 더 큰 애플리케이션을 확장하는 데 어떻게 도움이되는지 보여 주길 바랍니다.
내가 본 규칙 엔진에서 가장 큰 장점은 비즈니스 규칙 소유자가 프로그래머에게 부담을주지 않고 비즈니스 규칙을 구현할 수 있다는 것입니다. 이해 관계자로부터 지속적으로 피드백을 받고 빠른 반복을 거치는 민첩한 프로세스가 있더라도 비즈니스 규칙을 만드는 사람들이이를 구현하도록하여 얻을 수있는 효율성 수준을 달성하지 못할 것입니다.
또한 규칙이 코드에 포함 된 경우 간단한 규칙 변경으로 인해 발생할 수있는 재 컴파일-재 테스트-재배포주기를 제거 할 때 값을 과소 강조 할 수 없습니다. 빌드에 축복을 부여하는 데 관여하는 여러 팀이 종종 있으며 규칙 엔진을 사용하면 그 대부분을 불필요하게 만들 수 있습니다.
I've written a rules engine for a client. The biggest win was including all the stakeholders. The engine could run (or replay) a query and explain what was happening in text. The business people could look at the text description and quickly point out nuances in rules, exceptions, and other special cases. Once the business side was involved, the validation got much better because it was easy to get their input. Additionally, the rules engine can live separately from other parts of an application code base so you can use it across applications.
The con is that some programmers don't like to learn too much. Rule engines and the rules you put into them, along with the stuff that implements them, can be a bit hairy. Although a good system can easily handle sick and twisted webs of logic (or illogic often ;), it's not as simple as coding a bunch of if
statements (no matter what some of the simple-minded rule engines do). The rules engine gives you the tools to handle rule relationships, but you still have to be able to imagine all of that in your mind. Sometimes it's like living in the movie Brazil. :)
It (as everything else) depends on your application. For some applications (usually the ones that never change or the rules are best on real life constants, i.e. won't change noticeably in eons, for instance physical properties and formulae) it doesn't make sense to use a rule engine, it just introduces additional complexity and requires the developer to have a larger skill set.
For other applications it's really a good idea. Take for instance order processing (orders being anything from invoicing to processing currency transactions), every now and then there's a minute change to some relevant law or code (in the judicial sense) that requires you to fulfil a new requirement (for instance sales tax, a classic). Rather than trying to force your old application into this new situation where all the sudden you have to think about sales tax, where as before you didn't, it is easier to adapt your rule set rather than having to meddle about in potentially a large set of your code.
Then the next amendment from your local government requires reporting of all sales within a certain criteria, rather than you have to go in and add that, too. In the end you'll end up with very complex code that will prove pretty difficult to manage when you turn around and want to revert effect of one of the rules, without influencing all the others...
Everybody thus far has been very positive about rules engines, but I advise the reader to be wary. When a problem becomes a little bit more complicated, you may suddenly find that an entire rules engine has been rendered unsuitable, or much more complicated than in a more powerful language. Also, for many problems, rules engines will not be able to easily detect properties that greatly reduce the runtime and memory footprint of evaluating the condition. There are relatively few situations in which I would prefer a rule engine to a dependency injection framework or a more dynamic programming language.
"but really, how many apps really have that many changes?"
Honestly, every app I have worked on has gone through serious workflow and/or logic changes from concept until well after deployment. It's the number one reason for "maintenance" programming...
The reality is that you can't think of everything up front, hence the reason for Agile processes. Further, the BA's always seem to miss something vital until it's found in testing.
Rule Engines force you to truly separate business logic from presentation and storage. Further, if using the right engine, your BA's can add and remove logic as necessary. As Chris Marasti-Georg said, it puts the onus on the BA. But more than that, it allows the BA to get exactly what they are asking for.
A rules engine is a win on a configurable application where you don't want to have to do custom builds if it can be avoided. They are also good at centralising large bases of rules and algorithms like Rete are efficient for quickly matching against large rule sets.
Lots of good answers already but wanted to add a couple of things:
- in automating a decision of any complexity the critical thing rapidly becomes your ability to manage rather than execute the logic involved. A rules engine will not help with this - you need to think about the rule management capabilities that a business rules management system has. Most commercial and open source rules engines have evolved into rule management systems with repositories, reporting on rule usage, versioning etc. A repository of rules, structured into coherent rule sets that can be orchestrated to make business decisions is a lot easier to manage than either thousands of lines of code or a rule soup.
- There are many ways to use a declarative, rules-based approach. Using rules to manage a UI or as part of defining a process can be very effective. The most valuable use of a rules approach, however, is to automate business decisions and to deliver this as loosely coupled decision services that take input, execute rules and return an answer - a decision. Thing of these as services that answer questions for other services like "is this customer a good credit risk" or "what discount should I give this customer for this order or "what's the best cross sell for this customer at this time. These decision services can be very effectively built using a rules management system and allow for easy integration of analytics over time, something many decisions benefit from.
I see rule, process and data engines (a.k.a. databases) as essentially being similar. But, for some reason, we never say that blackboxing the persistence subsystem is bad.
Secondly, from my POV, an anemic model is not one that is light in implementation of behaviors, it is one that is light in behaviors itself. The actual method that describes an available behavior in a domain model object does not have to be done by the object itself.
The biggest complexity from my experience in Rule Engines is that:
- from OOP POV it's a real pain to refactor and test rules written in a declarative language while you are refactoring code that affects them.
- Often we should always think about the execution order of rules which turns into a mess when there are lots of them.
- Some minor changes may trigger incorrect behaviour of rules leading to production bugs. In practice it's not always possible to cover all cases with tests up front.
- Rules mutating objects used in other ones also increase complexity causing developers to break them into stages.
참고URL : https://stackoverflow.com/questions/250403/rules-engine-pros-and-cons
'program story' 카테고리의 다른 글
typescript와 함께 스프레드 구문 및 new Set () 사용 (0) | 2020.11.14 |
---|---|
객체 분해의 유형 (0) | 2020.11.14 |
비트 연산자와 "엔디안" (0) | 2020.11.14 |
설치되지 않은 RPM 패키지에 대한 정보를 표시합니까? (0) | 2020.11.14 |
Mac OS X의 시간 초과 명령? (0) | 2020.11.14 |