Сравнивайте с английским: нажмите на абзац — оригинал откроется в окне. Кнопка EN под абзацем показывает его прямо в тексте.
Содержание
Введение
Декларативный язык
Declarative language
Язык ограничений объектов (OCL) — это декларативный язык, описывающий правила, применимые к моделям Unified Modeling Language (UML), разработанным в IBM и являющийся сейчас частью стандарта UML. Изначально OCL был лишь формальным языком-расширением спецификации UML. В настоящее время OCL может использоваться с любой метамоделью группы управления объектами Meta Object Facility (MOF) (OMG), включая UML. Язык ограничений объектов — это точный текстовый язык, предоставляющий выражения ограничений и запросов к объектам для любой модели или метамодели MOF, которые нельзя выразить иным способом с помощью диаграммной нотации. OCL является ключевым компонентом новой рекомендации OMG по стандартизации преобразования моделей, спецификации Queries/Views/Transformations (QVT).
The Object Constraint Language (OCL) is a declarative language describing rules applying to Unified Modeling Language (UML) models developed at IBM and is now part of the UML standard. Initially, OCL was merely a formal specification language extension for UML. OCL may now be used with any Meta Object Facility (MOF) Object Management Group (OMG) meta model, including UML. The Object Constraint Language is a precise text language that provides constraint and object query expressions on any MOF model or meta model that cannot otherwise be expressed by diagrammatic notation. OCL is a key component of the new OMG standard recommendation for transforming models, the Queries/Views/Transformations (QVT) specification.
ОКЛ и UML
OCL дополняет UML, предоставляя выражения, лишенные неоднозначности, свойственной естественному языку, и сложности, присущей сложной математике. OCL также является языком навигации по графовым моделям.
OCL supplements UML by providing expressions that have neither the ambiguities of natural language nor the inherent difficulty of using complex mathematics. OCL is also a navigation language for graph based models.
ОКЛ и МОФ
OCL повышает точность модели Meta Object Facility, связывая утверждения с ее метаэлементами.
OCL makes a Meta Object Facility model more precise by associating assertions with its meta elements.
ОКЛ и QVT
Особое значение для разработки на основе моделей (MDE) или архитектуры, управляемой моделями, имеет понятие преобразования моделей. OMG определил специальный стандарт для преобразования моделей под названием MOF/QVT, или сокращенно QVT. В настоящее время существует несколько языков преобразования моделей, таких как GReAT, VIATRA или Tefkat, с различной степенью соответствия стандарту QVT. Многие из этих языков основаны на OCL, который является ключевым компонентом соответствия QVT.
Of particular importance to Model Driven Engineering (MDE) or model driven architecture is the notion of Model transformation. The OMG has defined a specific standard for model transformation called MOF/QVT or in short QVT. Several model transformation languages like GReAT, VIATRA, or Tefkat are presently available, with different levels of compliance with the QVT standard. Many of these languages are built on top of OCL, which is the main part of the QVT compliance.
Альтернативы
Будучи языком валидации, основанным на правилах, Schematron может рассматриваться как альтернатива OCL. Однако Schematron работает с деревьями Extensible Markup Language (XML), в то время как OCL позволяет осуществлять навигацию по моделям и метамоделям на основе MOF (т.е. деревьям XML Metadata Interchange (XMI)). Другими словами, OCL относится к UML или MOF аналогично тому, как Schematron относится к XML. (Обратите внимание, что Schematron использует XPath для навигации внутри XML-деревьев.) Язык спецификации моделей, позволяющий разработчикам дополнять модель или метамодель аннотациями без побочных эффектов, OCL может быть заменен такими языками, как Alloy. Автоматическая генерация OCL в принципе возможна на основе естественного языка. + ПримерыОграничениеЭквивалент OCLВозраст человека не может быть отрицательным. context Person inv: self.age >= 0Человек моложе своих родителей. context Person inv: self.parents->forAll(p | p.age > self.age)После дня рождения человек становится на год старше. context Person::hasBirthday post: self.age = self.age@pre + 1У человека не более двух родителей. context Person inv: self.parents->size <= 2После того, как у кого-то родился ребенок, его набор детей не пуст и больше, чем был ранее. context Person::getsChild post: self.children->notEmpty and self.children->size > self.children@pre->sizeТолько взрослый может быть владельцем автомобиля. context Person inv: self.age < 18 implies self.cars->isEmptyПервая регистрация автомобиля не может быть раньше его изготовления. context Auto inv: self.registration >= self.constructionYearКаждый человек, у которого есть автомобиль, имеет хотя бы один автомобиль, который моложе его. context Person inv: self.cars->notEmpty implies self.cars->exists(c | Calendar.YEAR - c.constructionYear < self.age)Никто не может быть своим собственным родителем. context Person inv: self.parents->excludes(self)Существует хотя бы один человек, владеющий автомобилем. context Person inv: Person.allInstances->exists(p | p.cars->size > 0)
Being a rule based validation language, Schematron may be considered an alternative to OCL. However Schematron works for Extensible Markup Language (XML) trees while OCL makes it possible to navigate MOF based models and meta models (i. e. XML Metadata Interchange (XMI) trees). In other words, OCL relates to UML or MOF similarly to how Schematron relates to XML. (Note that Schematron uses XPath to navigate inside the XML trees. )Being a model specification language permitting designers to decorate a model or a meta model with side effect free annotations, OCL could be replaced by languages like Alloy. Automated OCL generation is in principle possible from natural language. + ExamplesConstraintOCL EquivalentThe age of a person is not negative. context Person inv: self. age >=0A person is younger than its parents. context Person inv: self. parents >forAll(p|p. age>self. age)After a birthday, a person becomes one year older. context Person::hasBirthday post: self. age=self. age@pre+1A Person has 2 parents at max. context Person inv: self. parents >size <=2After somebody has a child, his/her child set is not empty, and it is larger than before. context Person::getsChild post: self. childs >notEmpty and self. childs >size > self. childs@pre >size Only an adult can be owner of a car. context Person inv: self. age<18 implies self. cars >isEmpty The first registration of a car can not be before it is built. context Auto inv: self. registration>=self. constructionYearEvery Person that has a car has at least one car which is younger than the Person. context Person inv: self. cars >notEmpty implies self. cars >exists( c | Calendar. YEAR c. constructionYear < self. age)Nobody can be his/her own parent. context Person inv: self. parents >excludes(self)There's at least one Person which owns a car. context Person inv: Person. allInstances >exists(p | p. cars >size > 0)
Расширения
Eclipse OCL расширяет стандартный OCL дополнительными операторами и типом для отображений (Maps). AgileUML расширяет стандартный OCL типами отображений (Map) и функций (Function). Эти расширения согласованы с типами отображений и функций, присутствующими в современных языках программирования, таких как Python и Swift.
Eclipse OCL extends Standard OCL with additional operators and a type for Maps. AgileUML extends Standard OCL with Map and Function types. These extensions are consistent with the map and function types present in modern programming languages such as Python and Swift.