Scala the default way to create objects that require a complex construction process - scala

I think its always useful to know the default practices that the language designers intended, and the default practices towards which they target language improvements, even if one later deviates from those conventions. In Scala all fields have to be initialised in the constructor of the class they're declared in. This is a a significant restriction. Secondary constructors are also restricted. Any temporary variables in a constructor need to be placed in an inner method or closure, to avoid unwanted fields, which can make the body of a constructor look messy. All this militates against using constructor bodies. The override val/var syntax needed even when assigning to abstract variables from a super class remove some of the advantage of using derived classes for the sake of construction.
A companion object has access to all the fields of its class. However for construction this is not the advantage that it might first appear, as all fields must be initialised in the constructor of the class. So it would seem the natural practice is to use a method in an object to do any processing of the classes variables, creating a temporary mutable collection for each immutable collection in the class, listbuffer being the default and then pass all the values and collections into a bodiless constructor. The factory can be in any object or even class but might as well be in the companion object unless there's a good reason otherwise. Objects can't take type parameters but their factory methods can if needed. And of course you can have as many factory methods as you need quasi-constructors and they can reuse any common algorithms.
Is this correct?
In response to the request for an example, here's a constructor I'm in the process of porting across to Scala from C#, note the multiple type parameters are gone in Scala:
public class GridC : GridBase<HexC, SideC, UnitC, ISegC>
{
public Geometry<HexC, SideC, UnitC, ISegC> geomC { get; private set; }
internal GridC(Scen scen, int gridNum, int xDim, int yDim, int xOff, int yOff, Terr terr = Terr.Plain):
base(gridNum, scen, 10.0)
{
this.geomC = scen.geomC;
xIntLeft = xOff + 1;
yIntBottom = yOff;
xIntRight = xDim * 2 + 1 + xOff;
yIntTop = yDim * 2 + 2 + yOff;
Coodg hexCoodg;
for (int x = xOff; x < xDim * 2 + xOff; x += 2)
{
for (int y = yOff; y < yDim * 2 + yOff; y += 2)
{
if (x % 4 == y % 4)
{
hexCoodg = new Coodg(num, x + 2, y + 2);
HexC hexC = scen.hexCs.NewHexC(hexCoodg);
SideC sideC;
MiscStrat.sixDirn.ForEach(i =>
{
Coodg sideCoodg = hexCoodg + Cood.DirnTrans(i);
sideC = sides[sideCoodg];
if (sideC == null)
scen.sideCs.NewSide(hexC, i);
else
scen.sideCs.SetHex2(sideC, hexC, i);
});
}
}
}
}
The above sub class is created purely to provide a constructor for the following base class edited just to show the parts relevant to construction;
public class GridBase<HexT, SideT, UnitT, SegT> : IGridBase
where HexT : Hex where SideT : Side where UnitT : Unit where SegT : ISeg
{
public int num { get; private set; }
int IGridBase.num { get { return num; } }
IListsGeom<HexT, SideT, UnitT> iLists;
public HexList<HexT> hexs { get { return iLists.hexs; } }
public SideList<SideT> sides { get { return iLists.sides; } }
public Geometry<HexT, SideT, UnitT, SegT> geom { get; private set; }
public int xIntLeft { get; protected set; }
public int xIntRight { get; protected set; }
public int yIntBottom { get; internal set; }
public int yIntTop { get; internal set; }
public double scale { get; private set; }
protected GridBase(int num, IListsGeom<HexT, SideT, UnitT> iLists, double scale)
{
this.num = num;
this.iLists = iLists;
this.scale = scale;
}
}
The constructor creates a simple uniform Hex grid. Other constructors were required that used a completely different algorithm and others will be created that require a related but more complex algorithms. I'm not an expert but my impression is that factories are used a lot less in C#.

If I understand your question, I'd say that something that needs a complicated construction method should have apply methods to support that on the companion object. However I'd be concerned that they have such complicated construction requirements.

In general, you usually provide complex construction like this through methods on the companion object of your (base) class. It provides a nice clean separation of the initialisation code and the post-construction usage code.
Also, having immutable data may help design smaller, more focused concerns. For instance you have a box (left, right, top, bottom) that you could separate into its own class (or just a tuple if you like).

About your statement that all fields must be initialized in the constructor of the class: you have two ways to cope with this.
Set the more complicated fields to a default value in the constructor of the class, e.g. val a: Int = _
Do the calculations in the apply method of the companion object and initialize all fields in the constructor (i.e., pass all those pre-computed values to the constructor)
Personally, I prefer 2. because it guarantees that an object is semantically complete after construction.

Related

Extract strongly-typed data context instance from arbitrary query

Background
We have a class library which has a grid (inherits from WPF DataGrid) with refresh functionality. The grid has a IQueryable Query property, which enables the refresh. Each grid's query is defined not in the class library, but in the referencing end-project:
var dg = new RefreshableDataGrid();
dg.Query = () => new ProjectDbContext().Persons;
Each grid also has a textbox for text filtering. When text is entered in the filter, an expression is generated which checks if any string property or string-convertible property (using SqlFunctions.StringConvert) contains the filter string. The expression is then appended to the original query as an argument to Where, and thus only the records containing matching strings are returned.
//within the class library
//pseudo-code -- this is actually done via reflection, because at compile time the
//actual type of the grid is not known, and there is no generic placeholder
this.ItemsSource = this.Query.Where(filterExpression)
In some cases, the filter logic is defined in end-projects, on the entity type. For example:
public interface IFilterable {
public Expression<Func<String, Boolean>> TextSearchExpression();
}
public class Email {
public int ID {get;set;}
public int PersonID {get;set;}
public string Address {get;set;}
}
public class Person : IFilterable
public int ID {get;set;}
public string LastName {get;set;}
public string FirstName {get;set;}
public Expression<Func<String, Boolean>> TextSearchExpression() {
Dim ctx = new ProjectDbContext();
return phrase => LastName.Contains(phrase) || FirstName.Contains(phrase) ||
ctx.Emails.Where(x => x.PersonID = ID && x.Address.Contains(prase).Any();
}
}
This expression tree uses an instance of the project-specific context, which is a different instance from that of the original query. Queries cannot use components from multiple contexts (at least not in Entity Framework). I can rewrite the expression tree to use a specific instance, but I need to extract the original instance from the query.
It seems obvious that the query holds some reference to the context instance, otherwise the query would not be able to return results.
I do not want to pass the context instance to the class library.
Hence:
Given a query, how can I get the strongly-typed DbContext instance used to create the query?
In other words, what goes in the body of this method:
DbContext GetDbContext<TSource>(IQueryable<TSource> qry) {
// ???
}
It seems obvious that the query holds some reference to the context instance, otherwise the query would not be able to return results.
That's true, but it's implementation specific detail and in EF is encapsulated inside internal members/classes/interfaces.
Also taking into account that DbContext is build on top of the ObjectContext, holding a reference to the DbContext is not strongly necessary. Fortunately that's not the case :)
The following uses reflection and implementation details of the latest EF6.1.3 (tested and working if you don't use some 3rd party extensions like LinqKit and similar that replace the query provider):
public static DbContext GetDbContext<TSource>(this IQueryable<TSource> query)
{
const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
var provider = query.Provider;
var internalContextProperty = provider.GetType().GetProperty("InternalContext", flags);
if (internalContextProperty == null) return null;
var internalContext = internalContextProperty.GetValue(provider, null);
if (internalContext == null) return null;
var ownerProperty = internalContext.GetType().GetProperty("Owner", flags);
if (ownerProperty == null) return null;
var dbContext = (DbContext)ownerProperty.GetValue(internalContext, null);
return dbContext;
}
I would recommend passing an instance of MyDataContext into your query function
public class DACPerson
{
public static IQueryable<Person> GetAllAsQueryable(MyDataContext db)
{
return db.People.AsQueryable();
}
}
This allows you to do the following in the calling function:
public List<Person> UpdateListofPeople(string term)
{
using(DataContext db = new DataContext())
{
var people = DACPerson.GetAllAsQueryable(db);
var result = people.Where(x=>x.Username.Contains(term)).
//call other Data Access Component FUnctions here using same DB....
}
}
i.e. you can bring the filtering to the layer above the data access class.
Some people may not like to do this. You may get the advice that its best to keep all entityframeowrk functionality within the same layer and just return the DTO. I like the above approach though. It depends on who will have to maintain each part of your application in the future.
Hope this helps at least

Adding Aspects to Derived Classes

I had wrote an aspect that works fine, but only on base classes, on derived classes do nothing.
Please, what I am missing?
The code is as follow
public interface INotifyOnChange : INotifyPropertyChanged
{
void OnPropertyChanged(string propertyName);
}
[Serializable]
[AspectConfiguration(AspectPriority = 10)]
[IntroduceInterface(typeof(INotifyOnChange), OverrideAction = InterfaceOverrideAction.Ignore, AncestorOverrideAction = InterfaceOverrideAction.Ignore)]
[MulticastAttributeUsage(MulticastTargets.Class, Inheritance = MulticastInheritance.Strict, AllowMultiple = false)]
public sealed class NotifyPropertiesOnChange : InstanceLevelAspect, INotifyOnChange
{
[IntroduceMember(Visibility = Visibility.Family, IsVirtual = true, OverrideAction = MemberOverrideAction.Ignore)]
public void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(Instance, new PropertyChangedEventArgs(propertyName));
[IntroduceMember(OverrideAction = MemberOverrideAction.Ignore)]
public event PropertyChangedEventHandler PropertyChanged;
[OnLocationSetValueAdvice, MulticastPointcut(Targets = MulticastTargets.Property, Attributes = MulticastAttributes.Public | MulticastAttributes.Instance)]
public void OnSetValue(LocationInterceptionArgs args)
{
if (args.Value == args.GetCurrentValue())
return;
args.ProceedSetValue();
var notifyOnChange = args.Instance as INotifyOnChange;
notifyOnChange?.OnPropertyChanged(args.Location.PropertyInfo.Name);
}
}
I had also tested with Inheritance = MulticastInheritance.Multicast without success.
However if I have a base class like the one here below it works
[NotifyOnChange]
public class EuroRate
{
public string Currency { get; set; }
public decimal Rate { get; set; }
public DateTime Date { get; set; }
}
but if try on a derived class (removing the aspect from the base class of course) it don't works
public class EuroRate
{
public string Currency { get; set; }
public decimal Rate { get; set; }
public DateTime Date { get; set; }
}
[NotifyPropertiesOnChange]
public class RateModel : EuroRate
{
}
An aspect can only alter the declaration on which it is applied. In case of your aspect (TypeLevelAspect) this means that when applied on RateModel class it can only apply advices on properties declared directly by this class. Properties declared by the base will not be transformed (as you would need to transform the base itself).
In this case, the best option is to rely on the multicast inheritance itself, i.e. apply the aspect on the base class. This would mean that you need to work with the fact that the aspect is applied separately on each class and develop a mechanism for communication between these aspects.
Performance concerns
You might have noticed that this would cause multiple instances of the aspect to exist for a single instance of the target class (depending on levels of inheritance).
You can optimize this by using combination of an instance-level aspect that introduces the OnPropertyChanged method, the event and the interface. This aspect would not be applied directly but through IAspectProvider by the main aspect that would be mere TypeLevelAspect.
Ad your Multicast Inheritance note (see the documentation):
For TypeLevelAspect applied on type [MulticastInheritance.Strict] and [MulticastInheritance.Multicast] are essentially the same.
The reason is that multicast inheritance also takes into account the declaration on which it was multicasted (inherits the multicast itself); i.e. if you apply method level aspect on a type, multicast inheritance will cause derived classes to inherit the aspect for all of its methods.
On the other the strict inheritance will cause only the applied aspect to be inherited, i.e. only overriding methods will have the aspect.

Calculated columns should be where in MVVM model?

I have a WPF DataGrid displaying Products. I have two fields price and mass in that which are actually the properties of Product class. I need to show a seperate column in grid name MultipliedValue = price * mass. As per MVVM model where should i do it ?
1) In model by making a readonly property.
2) In converter so that only my UI will be aware of that?
3) or in View model?
Please suggest which option i should choose and why?
Thanks.
I would disregard option #2 from the beginning -- converters should be used only to account for implementation details of the UI, and specifically in MVVM perhaps not even then (as you can do the conversion inside the ViewModel, which is option #3 and more convenient).
Between #1 and #3, in this case IMHO it's best to go with #1 -- price is not something that's only relevant for your UI and of course the concept of price (and how it is derived) is going to stay fixed throughout your application. Both the UI and your backend may choose to use this property or not.
I would argue differently (than #jon). I put in the model only properties that I would like to serialize (say, from the server). Computed properties don't serialize, and hence they aren't in the model.
Recently, my favorite Model/View Model paradigm as as follow: Product is a class in the Model, that has nothing but the simplest getters and setters. ProductVm is a class in the VM, which contains Product, and has the additional VM logic. Most importantly, the property changed notification - which in my opinion is also part of the VM and not the model.
// Model:
class Product {
public double Price { get; set; }
public double Mass { get; set; }
}
// View Model:
class ProductVM : INotifyPropertyChanged
{
Product _product;
public event PropertyChangedEventHandler PropertyChanged;
public double Price {
get { return _product.Price; }
set { _product.Price = value; raise("Price"); raise("Total"); }
}
public double Mass {
get { return _product.Mass; }
set { _product.Mass = value; raise("Mass"); raise("Total"); }
}
public double total {
get { return Price * Mass; }
}
private void raise(string name) {
if( PropertyChanged ) {
PropertyChanged( this, new PropertyChangedEventArgs(name) );
}
}
public ProductVm( Product p ) {
_product = p;
}
public ProductVm() {
// in case you need this
_product = new Product();
}
}
Yes, there is a lot of boilerplate here, but once you do all the typing, you'll find this separation between Model and ViewModel very helpful. My 2 cents.
Note: I think #Jon approach is also correct, and is reasons are valid. I don't think there is one answer.

ID based NPC system

I have a bunch of different npcs. They all have different properties and different AI, so I have made a separate class for each type, and derive it from a base class Entity. I want to make it so that I can assign an ID to each type of Entity, so I can just call CreateNewEntity(int id, Vector2 position). How would I do this? I also have a feeling that I'm designing this badly. Is that true
There are a couple of ways you could do this.
You could create an Attribute that will give the type some metadata such as ID
e.g.
public class RenderableEntity{
}
[EntityTypeAttribute(Name = "Wizard"]
public class Wizard : RenderableEntity{
}
you could then bundle them all in a namespace or a logical container and create the type as follows
pseudo:
//Create Entity
//Type Name
string entityName = "Wizard";
//Get the Type
from the namespace where the type has the custom attribute applied to it. Get the type
//Activator.Create(typeof(TheWizardType))
The other is that you could just get the Type where the name matches the string you passed into your create method.
Inheriting from a base entity sounds like a good approach. Anything that is shared between all your objects should be in the base entity, and anything that is specific to each type of NPC, should be in their own class. Things that have the same purpose, but different implementation (like AI, or CreateNewEntity) should be marked virtual, so the methods can be called from a list of base entities, but the correct implementation will run. CreateNewEntity should probably be a constructor.
example:
public class Entity
{
public int Id { get; protected set; }
public Vector2 Position { get; protected set; }
public int Strength { get; protected set; }
public Entity(int id, Vector2 position)
{
Id = id;
Position = position;
Strength = 1;
}
public virtual RunAI()
{
Position.X = Position.X + 1;
}
}
public class SuperHero
{
public SuperHero(int id, Vector2 position) : base (id, position)
{
Strength = 20;
}
public override void RunAI()
{
Position.X = Position.X + 500;
}
}
It sounds like the flyweight pattern would be beneficial here: http://www.primos.com.au/primos/Default.aspx?PageContentID=27&tabid=65
You probably want to differentiate the core state that makes each entity different and then put as much as possible in the shared instance.

Mixed vs. separated class mutability

In a partially mutable class, is it better to mix mutable fields with its immutable ones, or create a new class (or classes) that encapsulate them? Here's an example in C# of what I'm talking about:
interface IBedroom
{
int Volume { get; }
string Color { get; }
void Paint(string newColor);
}
Here's an implementation with mixed mutability in its fields:
class MixedMutabilityBedroom : IBedroom
{
readonly int volume;
string color;
public MixedMutabilityBedroom(int volume, string color = "")
{
this.volume = volume;
this.color = color;
}
public int Volume
{
get { return volume; }
}
public string Color
{
get { return color; }
}
public void Paint(string newColor)
{
color = newColor;
}
}
And one with separate mutability:
// first, a fully mutable helper class
class RoomColor
{
string value;
public RoomColor(string value)
{
this.value = value;
}
public string Value
{
get { return value; }
}
public void Change(string newValue)
{
value = newValue;
}
}
and the separated-mutability implementation:
class SeparatedMutabilityBedroom : IBedroom
{
readonly int volume;
readonly RoomColor color;
public SeparatedMutabilityBedroom(int volume, RoomColor color)
{
this.volume = volume;
this.color = color;
}
public int Volume
{
get { return volume; }
}
public string Color
{
get { return color.Value; }
}
public void Paint(string newColor)
{
color.Change(newColor);
}
}
I personally side with the latter style. In my experience, bugs that arise from state manipulation in concurrent scenarios are difficult to debug. As concurrency becomes the norm for programs, it seems that localizing mutability is a key factor to reducing debugging effort. In the second example we do not have to look over the entire class implementation to find out where state is manipulated. The entirety of SeparatedMutabilityBedroom's mutability is localized to RoomColor.
What do you think? Have I forgotten some points for consideration?
Programming with immutable data structures is a very useful technique but is hard to critique on an overall best practice or suggestion based on a simple example. Deciding what is best must take into account other factors such as how this class is being used and interacted with.
However, assuming you are in a situation that has a large amount of concurrency with multiple writers to this object, then making an object partially immutable really wont buy you much since you can still run into issues.
In that case either use some sort of synchronization primitive or use a completely immutable object.
This answer talks about some techniques of using completely immutable objects.