Shortcut syntax when directly implementing an interface - ceylon

Is it possible to implement the ceylon typechecker in such a way, that a class, that satisfies an interface directly (types in members signatures are the same as in the interface being satisfied), can omit types in its own members signatures?
This would help to reduce visual clutter at implementation site by moving all meta information (types, annotations) to the interface. And it helps to focus on implementation details.
This would be close to a signature file in ocaml.
And it could help to say more, more clearly.
Edited after the answer was given by Lukas Werkmeister:
What I'd like to have is a shortcut syntax that works not only for attributes but also for methods.
Look at "name(x)" in class Person:
interface Named {
shared formal String name(String n);
}
class Person(shared String firstName, shared String lastName) satisfies Named {
name(x) => firstName + x +" " + lastName;
}
Named named = Person("Lucas", "Werkmeister");
print(named.name);

This isn't allowed because it would be a bit too syntactically ambiguous. That is, it's impossible for the parser to distinguish name(x, y, z) from an invocation expression, until it finally hits the =>. This would result in some pretty undesirable behavior, for example, in the IDE when you start typing in a shortcut refinement, the parser would treat it as an invocation expression, and display errors on x, y, and on z.
In general we're very careful to make sure that we don't have any syntactic constructs that require too much lookahead to make sense of.

Yes, with the shortcut refinement syntax: you can simply write thing => ...; instead of shared actual Type thing => ...;. For exampled
interface Named {
shared formal String name;
}
class Person(firstName, lastName) satisfies Named {
shared String firstName;
shared String lastName;
name => firstName + " " + lastName;
// shortcut for
// shared actual String name => …;
}
Named named = Person("Lucas", "Werkmeister");
print(named.name);
Try online

Shortcut refinement does work with methods too, you just need to specify the parameter types:
interface Named {
shared formal String name(String n);
}
class Person(shared String firstName, shared String lastName) satisfies Named {
name(String x) => firstName + x +" " + lastName;
}

Related

Can you combine named parameter with short-hand constructor parameter?

In dart:
Named parameters function like so-
String send(msg, {rate: 'First Class'}) {
return '${msg} was sent via ${rate}';
}
// you can use named parameters if the argument is optional
send("I'm poor", rate:'4th class'); // == "I'm poor was sent via 4th class"
Short-hand constructor parameters function like so-
class Person {
String name;
// parameters prefixed by 'this.' will assign to
// instance variables automatically
Person(this.name);
}
Is there any way to do something like the below?-
class Person{
String name;
String age;
Person({this.name = "defaultName", this.age = "defaultAge"});
}
//So that I could do something like:
var personAlpha = new Person(name: "Jordan");
Thanks,
Code samples borrowed from dartlang synonyms
Update
Yes, the = is allowed in Dart 2 and is now preferred over the : to match optional positional parameters.
Person({this.name = "defaultName", this.age = "defaultAge"});
Old Answer
You just have to use a colon instead of equals
class Person {
String name;
String age;
Person({this.name: "defaultName", this.age: "defaultAge"});
}
I find this still confusing that optional parameters use = to assign defaults but named use :.
Should ask myself.
You can use the "this." syntax with all argument types.
As answered above, you need ':' for default values for named parameters.
You can even use "this." for function typed parameters:
class C {
Function bar;
C({int this.bar(int x) : foo});
static foo(int x) => x + 1;
}
You can also add an required field to skip the default initialization, like so:
class ProcessArguments {
final String logoImagePath;
final String textLogoImagePath;
ProcessArguments({required this.logoImagePath, required this.textLogoImagePath});
}

Mapping a field name beginning with an underscore in Entity Framework 4.1 Code First

I have a class that contains a few private/protected fields and some public getters that return the value of the fields. I am attempting to map the fields to database columns using the fluent API on the DbModelBinder in OnModelCreating. I cannot use an automatic property with a protected setter so please don't offer that as a solution to my question. It would probably work I'm sure but I cannot use the automatic property as the domain class is shared code and used with other different ORMs that have different ways of mapping their fields and unfortunately one doesn't support the au
I use the following code (found on stackoverflow) to access the protected field so that I can use the expression when mapping:
public static class ObjectAccessor<T>
where T : class
{
public static Expression<Func<T, TResult>> CreateExpression<TResult>(string propertyOrFieldName)
{
ParameterExpression param = Expression.Parameter(typeof(T), "propertyOrFieldContainer");
Expression body = Expression.PropertyOrField(param, propertyOrFieldName);
LambdaExpression lambda = Expression.Lambda(typeof(Func<T, TResult>), body, param);
return (Expression<Func<T, TResult>>)lambda;
}
}
This all works wonderfully if the field name is m_username but if I use _username I get a ModelValidationException: One or more validation errors were detected during model generation: System.Data.Edm.EdmProperty: Name: The specified name is not allowed: '_username'.
I can't use camelcase without the underscore either as the helper above can't distinguish between the public Username property and the protected username field. I'd really like to still keep using the underscore camelcase without the letter prefix.
Is it possible to configure the ModelBinder in some way so that the validation accepts the property name with a leading underscore?
Thanks in advance,
Mark
It seems that decoration of your field like this :
[Column("username")]
public string _username
maybe helpful in your case, anyway - please review similar case

List of OO languages where object immutability can be compiler enforced

Can anyone give me a list of languages where class immutability can be compiler enforced and tested easily ?
I need to be able to do something like:
class immutable Person {
private String name = "Jhon"; // lets say the String is mutable
public Person(String name) {
this.name = name; // ok
}
public void setName(String newName) {
this.name = newName; // does not compile
}
public void getName() {
return this.name; //returns reference through which name can't be mutated
}
private void testImmutability() {
getName().setFirstChar('a'); // does not compile
}
}
EDIT:
For a little more clarification, see here.
Functional programming languages like OCAML, Haskell, and Erlang.
F# and Scala both have the ability to created compiler-enforced immutable types (i.e. classes).
The following shows the basics in F#...
// using records is the easiest approach (but there are others)
type Person = { Name:string; Age:int; }
let p = { Person.Name="Paul";Age=31; }
// the next line throws a compiler error
p.Name <- "Paulmichael"
Here's the equivalent Scala. Note that you can still make mutable objects by using var instead of val.
class Person(val name: String, val age: Int)
val p = new Person("Paul", 31)
// the next line throws a compiler error
p.name = "Paulmichael"
Joe-E
From the language spec
3.4 Immutable Types
A type T is immutable if and only if it implements
the marker interface org.joe_e.Immutable according to the overlay
type system. The (empty) org.joe_e.Immutable interface must be provided
by the Joe-E implementation. The
intuition behind an immutable object
is that such an object cannot be
changed (mutated) in any observable
way, nor can any objects reachable by
following the elds of the immutable
object. The contents of an immutable
objects' elds and any objects
reachable from an immutable object
must not change once the object is
constructed. With the exception of
library classes explicitly deemed to
implement Immutable, an immutable
class must satisfy additional
linguistic restrictions enforced by
the verier (x4.4) to ensure this
property. Library classes that cannot
be automatically verified and are
deemed immutable must be carefully
manually veried to expose no
possibility for modication of their
contents. Note that immutability does
not place any restrictions on any
local variables dened within the
immutable class. It also says nothing
about the mutability of the arguments
passed to methods. It only applies to
the values stored in and objects
reachable from the immutable class's
elds
It also introduces useful notions of powerless, and selfless types.
The D (version D2) programming language has immutability. It has OOP, but immutability is rather a concept from functional pl. There it's called purity.

Proper usage of "this." keyword in C#?

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.
Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).
Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?
Thanks!
Personally I only use it when I have to which is:
Constructor chaining:
public Foo(int x) : this(x, null)
{
}
public Foo(int x, string name)
{
...
}
Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)
public void SetName(string name)
{
// Just "name = name" would be no-op; within this method,
// "name" refers to the parameter, not the field
this.name = name;
}
Referring to this object without any members involved:
Console.WriteLine(this);
Declaring an extension method:
public static TimeSpan Days(this int days)
{
return TimeSpan.FromDays(days);
}
Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.
StyleCop's default coding style enforces the following rule:
A1101: The call to {method or property
name} must begin with the 'this.'
prefix to indicate that the item is a
member of the class.
Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.
I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):
public void compareTo(MyClass other) {
if (this.someField > other.someField) return 1;
if (this.someField < other.someField) return -1;
return 0;
}
As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:
class Rect {
private int width, height;
public Rect(int w, int h) {
width = w;
height = h;
}
}
Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.
It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.
Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:
private String _someData;
public String SomeData
{
get{return _someData;}
set{_someData = value;}
}
It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.
So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.
The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)
If you have a method inside a class which uses same class's fields, you can use this.
public class FullName
{
public string fn { set; get; }
public string sn { set; get; }
//overriding Equals method
public override bool Equals(object obj)
{
if (!(obj is FullName))
return false;
if (obj == null)
return false;
return this.fn == ((FullName)obj).fn &&
this.sn == ((FullName)obj).sn;
}
//overriding GetHashCode
public override int GetHashCode()
{
return this.fn.GetHashCode() ^ this.sn.GetHashCode();
}
}

When should i consider using named parameters against normal parameters?

I was splitting RenameFolder to two pieces and i notice visual studios 2010 supports named parameters! (example below).
I know this has existed for a number of years in other languages. I remember a professor saying why he likes named parameters and that he uses them in all of his code. But i am sure its not in all of his code. I was wondering.
When should i consider to write the function using a named parameter vs normal style (func(a,b,c)). Some cases area (without a when and when not suggestion)
Calling public methods in the same class
Calling private methods in the same class
Calling methods in external 3rd party libraries
Calling methods in another class in the same namespace
Calling methods in another class in a different namespace or module
Calling methods from internal classes not meant to be a library
public bool RenameFolderIn(PK folderId, string newfoldername)
{
return RenameFolder(newfoldername: newfoldername, infolder: true, folderId: folderId);
}
public bool RenameFolderOut(PK folderId, string newfoldername)
{
return RenameFolder(newfoldername: newfoldername, infolder: false, folderId: folderId);
}
public bool RenameFolder(PK folderId, string newfoldername, bool infolder)
{
Typically, I use named parameters when there are a large number of default values and I only need to specify a few non-default, or when the function name doesn't suggest the order of parameters. In the example RenameFolder* functions, I would expect the folder to come before the new name (RenameFolder can be short for the phrase "rename folder folder to name"; phrasing it so the name comes first, if possible, isn't the obvious approach), and so wouldn't bother with named parameters.
Example: suppose Gamma is a constructor for the Gamma distribution, which hase two parameters: shape and scale. There's a statistical convention for passing shape before scale, but the convention isn't obvious from the name, so we use named parameters.
waitTime = Gamma(shape: 2, scale: 2)