Ajuda com criação de Diagrama de classes e de sequência

Olá, tenho esta atividade para entregar e gostaria de tirar algumas dúvidas.

A descrição é a seguinte: Uma faculdade tem vários cursos, um curso pode ter várias turmas, e vários professores, porém uma turma precisa de no mínimo um professor para existir. Para que uma turma seja formada ela deve ter um nome e são necessários no mínimo 5 alunos. Um professor deve ter nome, cpf e graduação (onde coloco qual curso superior aquele professor se graduou). Um aluno tem nome e cpf. Para que um professor lecione em uma turma ele deve ser da mesma graduação do curso daquela turma. Ou seja, para o professor lecionar em uma turma de sistemas de informação ele deve ser graduado em sistemas de informação. Considere o cenário do cadastro de uma turma e desenhe um protótipo de tela, um diagrama de classes e um diagrama de sequência, ambos baseando-se na arquitetura BCE.

Já fiz um protótipo e um diagrama de classes.

Protótipo: https://marvelapp.com/494bb0h Diagrama de Classes: https://www.lucidchart.com/invitations/accept/c375dd39-fcaa-40c8-a753-1e8d20133c76

As perguntas são as seguintes: Este diagrama de classes está de acordo com o pedido? Como começo a fazer o diagrama de sequência a partir do protótipo?

Categorising problems into complexity classes

Am I correct in saying that there are two ways to categorise a problem in complexity theory:

  • Find an algorithm that solves it. If the algorithm runs in polynomial time, then we can put it into P-class. If not, then we can put it into EXP.

  • Provide a reduction that this problem is no hard than another problem, to which we know the complexity class for.

If I cannot find a reduction and I do not have an algorithm, what is the “default” complexity class? I’m guessing it would be in the class of problems which cannot be solved until we find an algorithm.

Best practice when creating classes that are solely in charge of the creation of other objects i.e. factories?

I often find myself creating classes that I suffix with ‘Factory’. These classes tend to be solely in charge of the creation of a specific class or set of related classes. However I’ve always felt that this probably isn’t best practice and that there’s a better way of approaching this. One of the reasons that I believe that this isn’t best practice is down to the fact that although I am using the ‘factory’ suffix I am not actually making use of the factory design pattern.

Let’s say I have an class vehicle, that contains two variables make and model. I want my problem to be able to create a number of these vehicle objects, so I want to encapsulate the code to create these objects in a single class. I might create the below class.

public class VehicleFactory {     public Vehicle CreateVehicle(string make, string model)     {          //create vehicle..          return vehicle;     } } 

The VehicleFactory can then be used wherever I want in my program without repeating the code and violating DRY.

I often need to create these kind of factory classes when I’m refactoring code, more specifically when I find two or more classes that are creating the same objects. I’d want to refactor the code by pulling out the repeated code and then placing it inside a specific factory class.

Is there a better way to approach this issue?

Python: Exceptions versus Gaurd Classes

I’m trying to get my head around Python Exceptions. I’ve read quite a bit on the topic but can’t get clear answers to some questions. In particular, I’m still not sure whether to use exceptions or guard clauses for dealing with invalid arguments.

I know that this topic is, in general, a big debate with no clear answer. But I’m interested in whether Python in particular, as a language or as a community, has adopted a clear “best practice” answer.

It seems that Python is more lax with exceptions and in fact encourages them to be used for control flow. Eg, the StopIterationError. Does this extend to using exceptions to handle argument validation?

Here is a sample function I’m looking at:

def add_document(data: dict, country: str):     """Writes document to the database.     """      # Gaurd clauses     if data.get('Name', None) is None: log.warn("Name is none. Returning"); return     if data.get('url', None) is None: log.warn("URL is none. Returning"); return     <do write> 

To me, getting an invalid argument is not “exceptional”. It is actually expected to happen about 10% of the time. And yet, I still seem to want to warn the user/programmer about it (I wrote this function a year ago and am looking at it again now). Should it therefore fail more loudly? Does Python Zen “Errors should never pass silently.” apply here? Or should exceptions still be reserved for cases where either they have to be handled, or the software must be made to terminate?

Extending functionality of existing classes without breaking consumer code

Here is a set of classes that are used to build where clause for SQL Server and Oracle for different field types e.g. text, numeric and date.

public interface IConditionBuilder {     bool CanHandle(FilterAction filterAction);      string BuildCondition(SearchCondition filterCondition); }  public abstract class ConditionBuilder<TContext> : IConditionBuilder where TContext : FieldSearchContext {     public abstract string OperatorSymbol { get; }      public string BuildCondition(SearchCondition searchCondition)     {         var conditionBuilder = new StringBuilder();          var context = searchCondition.GetContext<TContext>();          conditionBuilder.Append(context.FieldId);         conditionBuilder.Append(OperatorSymbol);         conditionBuilder.Append(GetValue(context));          return conditionBuilder.ToString();     }      public abstract bool CanHandle(FilterAction filterAction);      public abstract object GetValue(TContext context);  }  public class TextLikeConditionBuilder : ConditionBuilder<TextContext> {     public override string OperatorSymbol => " LIKE ";      public override bool CanHandle(FilterAction action) => action == FilterAction.TextLike;      public override object GetValue(TextContext context)     {         if (context.Text == null)         {             return null;         }          return string.Concat("%", context.Text, "%");     } }  public class TextEqualsConditionBuilder : ConditionBuilder<TextContext> {     public override string OperatorSymbol => " = ";      public override bool CanHandle(FilterAction action) => action == FilterAction.TextEqual;      public override object GetValue(TextContext context)     {         if (context.Text == null)         {             return null;         }          return "'" + context.Text + "'";     } }  public class NumericLessThanConditionBuilder : ConditionBuilder<NumericContext> {     public override string OperatorSymbol => " < ";      public override bool CanHandle(FilterAction action) => action == FilterAction.NumericLessThan;      public override object GetValue(NumericContext context)     {         return context.Number;     } }  public class DateGreaterThanAndLessThanEqualConditionBuilder : IConditionBuilder {     public const string GREATER_THAN = " > ";      public const string LESS_THAN_EQUAL = " <= ";      public string BuildCondition(SearchCondition filterCondition)     {         var conditionBuilder = new StringBuilder();          var context = filterCondition.GetContext<DateContext>();          conditionBuilder.Append(context.FieldId);         conditionBuilder.Append(GREATER_THAN);         conditionBuilder.Append("'" + context.FromDate + "'");         conditionBuilder.Append(LESS_THAN_EQUAL);         conditionBuilder.Append("'" + context.EndDate + "'");         return conditionBuilder.ToString();     }      public bool CanHandle(FilterAction action) => action == FilterAction.DateGreaterThanLessThan;  } 

I want to extend the functionality so that context.FieldId is sanitized before it is used to build the condition statement for e.g. these classes will build a statement like Name = 'Aashish', I want the classes to build statement as [Name] = 'Aashish'. These classes are consumed by other developers so I don’t want to break the functionality for consumers as a result of the changes I will make, basically adhere to Open-Closed principle. So, here is how I implemented these changes. Notice how I added a virtual function SanitizeFieldId in ConditionBuilder and DateGreaterThanAndLessThanEqualConditionBuilder.

public abstract class ConditionBuilder<TContext> : IConditionBuilder where TContext : FieldSearchContext {     public abstract string OperatorSymbol { get; }      public string BuildCondition(SearchCondition searchCondition)     {         var conditionBuilder = new StringBuilder();          var context = searchCondition.GetContext<TContext>();          conditionBuilder.Append(SanitizeFieldId(context.FieldId));         conditionBuilder.Append(OperatorSymbol);         conditionBuilder.Append(GetValue(context));          return conditionBuilder.ToString();     }      public abstract bool CanHandle(FilterAction filterAction);      public abstract object GetValue(TContext context);      protected virtual string SanitizeFieldId(string fieldId)     {         return fieldId;     } }  public class DateGreaterThanAndLessThanEqualConditionBuilder : IConditionBuilder {     public const string GREATER_THAN = " > ";      public const string LESS_THAN_EQUAL = " <= ";      public string BuildCondition(SearchCondition filterCondition)     {         var conditionBuilder = new StringBuilder();          var context = filterCondition.GetContext<DateContext>();          conditionBuilder.Append(SanitizeFieldId(context.FieldId));         conditionBuilder.Append(GREATER_THAN);         conditionBuilder.Append("'" + context.FromDate + "'");         conditionBuilder.Append(LESS_THAN_EQUAL);         conditionBuilder.Append("'" + context.EndDate + "'");         return conditionBuilder.ToString();     }      public bool CanHandle(FilterAction action) => action == FilterAction.DateGreaterThanLessThan;      protected virtual string SanitizeFieldId(string fieldId)     {         return fieldId;     } }  public class SanitizedFieldConditionBuiler<TContext> : ConditionBuilder<TContext> where TContext : FieldSearchContext {     private ConditionBuilder<TContext> _baseConditionBuilder;     private IColumnSanitizer _columnSanitizer;      public SanitizedFieldConditionBuiler(ConditionBuilder<TContext> baseConditionBuilder, IColumnSanitizer columnSanitizer)     {         _baseConditionBuilder = baseConditionBuilder;         _columnSanitizer = columnSanitizer;     }      public override string OperatorSymbol => _baseConditionBuilder.OperatorSymbol;      public override bool CanHandle(FilterAction filterAction) => _baseConditionBuilder.CanHandle(filterAction);      public override object GetValue(TContext context) => _baseConditionBuilder.GetValue(context);      protected override string SanitizeFieldId(string fieldId)     {         return _columnSanitizer.Sanitize(fieldId);     } }  public class SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder : DateGreaterThanAndLessThanEqualConditionBuilder {     private IColumnSanitizer _columnSanitizer;      public SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder(IColumnSanitizer columnSanitizer)     {         _columnSanitizer = columnSanitizer;     }      protected override string SanitizeFieldId(string fieldId)     {         return _columnSanitizer.Sanitize(fieldId);     } } 

I use extension methods to initialize SanitizedFieldConditionBuilerand SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilderas shown below:

public static class Extensions     {         public static SanitizedFieldConditionBuiler<TContext> SanitizeField<TContext>(this ConditionBuilder<TContext> source, IColumnSanitizer columnSanitizer) where TContext : FieldSearchContext         {             return new SanitizedFieldConditionBuiler<TContext>(source, columnSanitizer);         }          public static SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder SanitizeField(this IConditionBuilder source, IColumnSanitizer columnSanitizer)         {             return new SanitizedDateFieldGreaterThanAndLessThanEqualConditionBuilder(columnSanitizer);         }      } 

The Sanitization is available by means of an interface IColumnSanitizer and has two different implementations, for Sql Server and Oracle respectively

 public interface IColumnSanitizer     {         string Sanitize(string columnName);     }      public class SqlSanitizer : IColumnSanitizer     {         public string Sanitize(string columnName)         {             return "[" + columnName + "]";         }     }      public class OracleSanitizer : IColumnSanitizer     {         public string Sanitize(string columnName)         {             return "\"" + columnName + "\"";         }     } 

Below is how context classes are implemented:

public abstract class FieldSearchContext {     public virtual string FieldId { get; }      protected FieldSearchContext(string fieldId)     {         FieldId = fieldId;     } }  public class DateContext : FieldSearchContext {     public DateContext(string fieldId, DateTime? fromDate, DateTime? endDate) : base(fieldId)     {         FromDate = fromDate;         EndDate = endDate;     }      public DateTime? FromDate { get; }      public DateTime? EndDate { get; } }  public class TextContext : FieldSearchContext {     public TextContext(string fieldId, string text) : base(fieldId)     {         Text = text;     }      public string Text { get; } }  public class NumericContext : FieldSearchContext {     public NumericContext(string fieldId, decimal number) : base(fieldId)     {         Number = number;     }      public decimal Number { get; } } 

These changes work perfectly fine but I want to find out if this can be achieved in a different and better way.

Use the code below to see it in action:

 class Program     {         static void Main(string[] args)         {             var conditions = new List<SearchCondition>()             {                 new SearchCondition(new NumericContext("Numeric Field", 1234), FilterAction.NumericLessThan),                 new SearchCondition(new TextContext("Text Field", "ASDF"), FilterAction.TextEqual),                 new SearchCondition(new TextContext("Text Field", "QWERTY"), FilterAction.TextLike),                 new SearchCondition(new DateContext("Date Field", DateTime.Now, DateTime.Now.AddYears(1)), FilterAction.DateGreaterThanLessThan)             };              Console.WriteLine(BuildWhereClause(Operation.AND, conditions));             Console.Read();         }          private static string BuildWhereClause(Operation operation, IList<SearchCondition> conditions)         {             var returnValue = new List<string>();             var conditionBuilders = new List<IConditionBuilder>()             {                 new TextEqualsConditionBuilder().SanitizeField(new SqlSanitizer()),                 new NumericLessThanConditionBuilder().SanitizeField(new SqlSanitizer()),                 new TextLikeConditionBuilder().SanitizeField(new SqlSanitizer()),                 new DateGreaterThanAndLessThanEqualConditionBuilder().SanitizeField(new SqlSanitizer())             };              foreach (var condition in conditions)             {                 var context = condition.GetContext<FieldSearchContext>();                 var conditionBuilder = conditionBuilders.FirstOrDefault(u => u.CanHandle(condition.FilterAction));                 returnValue.Add(conditionBuilder.BuildCondition(condition));             }              if (returnValue.Any())                 return string.Join(Convert.ToString(" " + operation + " "), returnValue);              return string.Empty;         }     }      enum Operation : int     {         AND = 1,         OR = 2     } 

What’s the exact consistency strength of this very elegant axiom system for classes and sets?

Notation: Let $ \phi$ be any formula in $ \small \sf FOL$ $ \small(=,\in, W)$ ; let $ \varphi$ be any formula in $ \small\sf FOL$ $ \small (=,\in)$ having $ x$ free, and whose parameters are among $ x_1,..,x_n$ .

Define: $ elm(y)\iff \exists z (y \in z)$

Where $ “elm”$ is short for “..is an element”

Axioms:

1.Extensionality: $ \forall z (z \in x \leftrightarrow z \in y) \to x=y$

2.Class Comprehension: $ \exists x \forall y (y \in x \leftrightarrow elm(y) \land \phi)$

3.Set Comprehension: $ x_1,..,x_n \in W \to [ \forall x (\varphi \to x \subseteq W) \leftrightarrow \forall x (\varphi \to x \in W)]$

4.Foundation: $ x \neq \emptyset \to \exists y \in x (y \cap x = \emptyset)$

5.Choice over all classes.

The basic two axioms of this theory are the two schemes, all the rest of axioms are indeed interpretable from them. $ W$ stands for the class of all sets, that’s why the predicate $ elm$ is used here instead of the usual denotation of it as $ set$ in Morse-Kelley class theory.

In my own personal opinion, this kind of axiomatization is ideal, I think it’s of the most elegant ones. There is no dispute over axioms 1,4,and 5. Schema 2 is the most natural principle about classes. Schema 3 technically sums up all of what’s in standard set theory in a neat manner. All axioms are very clean and fairly natural.

Question: What’s the exact consistency strength of this theory?

Number of equivalence classes in $P$

I am currently taking a course which involves computational complexity. I was told that under polynomial equivalence (polynomial time reduction) divides P into exactly 3 equivalent classes, namely $ \phi$ , $ \Sigma^*$ and $ P – \{\phi,\Sigma^*\}$ . I am unable to figure out how this is true, specifically how if $ L_1,L_2 \in P, L_1 \sim_P L_2$ . I think there’s a simple fact/idea I am missing out on, but I don’t know what it is.

Why prefer non-static inner classes over static ones?

This question is about whether to make a nested class in Java to be a static nested class or an inner nested class. I searched around here and on Stack Overflow, but couldn’t really find any questions regarding the design implications of this decision.

The questions I found are asking about the difference between static and inner nested classes, which is clear to me. However, I have not yet found a convincing reason to ever use a static nested class in Java — with the exception of anonymous classes, which I do not consider for this question.

Here’s my understanding of the effect of using static nested classes:

  • Less coupling: We generally get less coupling, as the class cannot directly access its outer class’s attributes. Less coupling generally means better code quality, easier testing, refactoring, etc.
  • Single Class: The class loader need not take care of a new class each time, we create an object of the outer class. We just get new objects for the same class over and over.

For an inner class, I generally find that people consider access to the outer class’s attributes as a pro. I beg to differ in this regard from a design point of view, as this direct access means we have a high coupling and if we ever want to extract the nested class into its separate top-level class, we can only do so after essentially turning it into a static nested class.

So my question comes down to this: Am I wrong in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and that I infer from this that (non-anonymous) nested classes should generally be static?

Or in other words: Is there a convincing reason why one would prefer a nested inner class?

What do the different data types in C++ classes do? (Private, public, and protected)

I have been trying to learn about classes and objects in C++, but every tutorial I have found is quite complex, at least to my standards, and I really would like a really simple and straight forward explanation explaining this. Like yeah, “private members are not accessible outside the class”, but how do I use them then. “The public members form an interface to the class and are accessible outside the class,” so can I just call them like [insert Class Name].[insert class instance], or insert object Name].[insert class instance]. These questions are probably pretty dumb, and my formatting is probably really bad, but I really wanna learn this language and I am new here.

Thanks for your help 🙂

How can we make a UML diagram (or something similar) for a project which doesn’t contains classes (like non object oriented)?

I am working on a python project and I didn’t use classes but created different modules and added functions in them.

Now I need to draw a diagram to describe the project/application for a paper. I already have a context level diagram and activity diagram. But now I need to describe the functional implementation of the application with a diagram.

I have searched a lot but can’t find a single (widely accepted) way!

It is a Django Project of an quiz application which is integrable with MOOCs like Canvas, Open edX... etc using LTI (Learning Tools Interoperability). Link to code: GitHub.com/anitagoel/iQuiz

Remember that even though the code is not object oriented, but the modules are there which contains all the functions related to specific functionality in the application. For example, there is a file students.py which handles Students, there is another module teachers.py which manages teachers view.

Can I create a UML like a class diagram with module name instead of class name, and then put the functions in the modules? Will it be valid knowing that it is meant for a research paper!?