Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Model Classes contain Methods, and Constructor

Tags:

c#

Q: `Can Model Classes contain Methods, and Constructor ?" [BEST PRACTICE]

I have an employee Model class which consists of the Employee's name, age, salary etc...

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Salary { get; set; }
}

so can the above Model Class contain some self updating methods [like updating the employee's age every 1 hour with a timer or something] and\or constructors or it is better to handle all that things from the executer ?

like image 849
Roman Ratskey Avatar asked Nov 04 '13 23:11

Roman Ratskey


People also ask

What is model class MVC?

The model classes represents domain-specific data and business logic in the MVC application. It represents the shape of the data as public properties and business logic as methods. In the ASP.NET MVC Application, all the Model classes must be created in the Model folder.

What do we write in model class?

A model class is typically used to "model" the data in your application. For example you could write a Model class that mirrors a database table , or a JSON . You could use objects of these classes as vessels to send / receive data. As an example this tool allows you top generate model java classes for JSON .

What should the model contain?

Models should contain logic that deals with manipulating data. For example, say we have a post model, the model should contain methods that get the comments of a particular post. In Sails models, each model has static methods like find , findOne , update , etc.

Can we write a method inside a constructor in Java?

Solution 1. A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance. Be aware that if a method constructs a new object of the same type, then calling that method from a constructor may result in an infinite loop...


2 Answers

Why couldn't they? The real answer is: it depends on your use case. Patterns, such as something being a model class, are recommendations, common ways of doing things, not unbreakable dogmas.

Note: The example “updating the employee's age every 1 hour with a timer or something” is fundamentally wrong. Storing age is fundamentally wrong, unless you are storing a snapshop to some moment in time. A much better solution would be to store date of birth, and compute the age. For example, by defining an Age property with a getter only.

like image 166
Ondrej Tucny Avatar answered Sep 30 '22 03:09

Ondrej Tucny


A model should contain all logic related to the model (this is DSL) so, yes it can update itself each hour. and when u define auto properties, it's same as defining setters and getter, so of course you can add methods, and constructors as well.

like image 38
Chen Kinnrot Avatar answered Sep 30 '22 04:09

Chen Kinnrot