Specification Pattern and Boolean Operator Precedence - operator-precedence

In our project, we have implemented the Specification Pattern with boolean operators (see DDD p 274), like so:
public abstract class Rule {
public Rule and(Rule rule) {
return new AndRule(this, rule);
}
public Rule or(Rule rule) {
return new OrRule(this, rule);
}
public Rule not() {
return new NotRule(this);
}
public abstract boolean isSatisfied(T obj);
}
class AndRule extends Rule {
private Rule one;
private Rule two;
AndRule(Rule one, Rule two) {
this.one = one;
this.two = two;
}
public boolean isSatisfied(T obj) {
return one.isSatisfied(obj) && two.isSatisfied(obj);
}
}
class OrRule extends Rule {
private Rule one;
private Rule two;
OrRule(Rule one, Rule two) {
this.one = one;
this.two = two;
}
public boolean isSatisfied(T obj) {
return one.isSatisfied(obj) || two.isSatisfied(obj);
}
}
class NotRule extends Rule {
private Rule rule;
NotRule(Rule obj) {
this.rule = obj;
}
public boolean isSatisfied(T obj) {
return !rule.isSatisfied(obj);
}
}
Which permits a nice expressiveness of the rules using method-chaining, but it doesn't support the standard operator precedence rules of which can
lead to subtle errors.
The following rules are not equivalent:
Rule<Car> isNiceCar = isRed.and(isConvertible).or(isFerrari);
Rule<Car> isNiceCar2 = isFerrari.or(isRed).and(isConvertible);
The rule isNiceCar2 is not satisfied if the car is not a convertible, which can be confusing since if they were booleans isRed && isConvertible || isFerrari would be equivalent to isFerrari || isRed && isConvertible
I realize that they would be equivalent if we rewrote isNiceCar2 to be isFerrari.or(isRed.and(isConvertible)), but both are syntactically correct.
The best solution we can come up with, is to outlaw the method-chaining, and use constructors instead:
OR(isFerrari, AND(isConvertible, isRed))
Does anyone have a better suggestion?

Your "constructor" solution sounds about right (semantically at least), in that it forces building something closer to an expression tree than a chain. Another solution would be to pull the evaluation functionality out of the Rule implementations so precedence can be enforced (by walking the chain).

Related

How can I solve 'Duplicate Constructor' error in Haxe?

In Haxe, I created a class named MyClass like:
class MyClass {
var score: String;
public function new (score: Int) {
this.score = Std.string(score);
}
public function new (score: String) {
this.score = score;
}
}
I need multiple constructors but Haxe does not allow me to do. It throws this error from building phase:
*.hx:*: lines * : Duplicate constructor
The terminal process terminated with exit code: 1
How can I solve this problem?
This is known as method overloading, which is not supported by Haxe apart from externs (but might be in the future). There's multiple ways you could work around this.
A common workaround in the case of constructors would be to have a static "factory method" for the second constructor:
class MyClass {
var score:String;
public function new(score:String) {
this.score = score;
}
public static function fromInt(score:Int):MyClass {
return new MyClass(Std.string(score));
}
}
You could also have a single constructor that accepts both kinds of arguments:
class MyClass {
var score:String;
public function new(score:haxe.extern.EitherType<String, Int>) {
// technically there's no need for an if-else in this particular case, since there's
// no harm in calling `Std.string()` on something that's already a string
if (Std.is(score, String)) {
this.score = score;
} else {
this.score = Std.string(score);
}
}
}
However, I wouldn't recommend this approach, haxe.extern.EitherType is essentially Dynamic under the hood, which is bad for type safety and performance. Also, EitherType is technically only intended to be used on externs.
A more type-safe, but also slightly more verbose option would be haxe.ds.Either<String, Int>. Here you'd have to explicitly call the enum constructors: new MyClass(Left("100")) / new MyClass(Right(100)), and then use pattern matching to extract the value.
An abstract type that supports implicit conversions from String and Int might also be an option:
class Test {
static function main() {
var s1:Score = "100";
var s2:Score = 100;
}
}
abstract Score(String) from String {
#:from static function fromInt(i:Int):Score {
return Std.string(i);
}
}
Finally, there's also an experimental library that adds overloading support with macros, but I'm not sure if it supports constructors.
I recommend to use type parameter
class MyClass<T> {
var score:String;
public function new(score:T) {
this.score = Std.string(score);
}
}
You can also use type parameter at constructor
class MyClass {
var score:String;
public function new<T>(score:T) {
this.score = Std.string(score);
}
}
However, T used at constructor fails at runtime (CS and Java), it is not fixed yet (Haxe 4). Otherwise, you could do this
class MyClass {
var score:String;
#:generic public function new<#:const T>(score:T) {
this.score = Std.is(T, String) ? untyped score : Std.string(score);
}
}
which nicely produce code like this (CS)
__hx_this.score = ( (( T is string )) ? (score) : (global::Std.#string(score)) );
causing Std.string() to be called only if T is not a String.
Hej,
With a simple example as it is, you can just do something like that function new( ?s : String, ?n : Int ){} and Haxe will use the correct argument by type. But you'll be able to do new() and maybe you don't want.

How to use the same #jsonproperty name int following example?

At any point of time i will be setting only one setter method but the JsonProperty name should be same for both . when i am compiling this i am getting an exception. How to set the same name for both .?
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
Jackson tends to favor common scenarios and good design choices for annotation support.
Your case represents a very uncommon scenario. You have one field having two different meanings in different contexts. Typically this would not be a favourable data format since it adds messy logic to the consumer on the other end...they need to divine what the "Json" property should mean in each case. It would be cleaner for the consumer if you just used two different property names. Then it would be sufficient to simply check for the presence of each property to know which alternative it's getting.
Your Java class also seems poorly designed. Classes should not have this type of context or modes, where in one context a field is allowed, but in another context it's not.
Since this is primarily a smell with your design, and not serialization logic, the best approach would probably be to correct your Java class hierarchy:
class BaseClass {
}
class SubClassWithItems {
public List<TwoDArrayItem> getItems() {
return items;
}
#JsonProperty("Json")
public void setItems(List<TwoDArrayItem> items) {
this.items = items;
}
}
class SubClassWithType {
public String getType() {
return type;
}
#JsonProperty("Json")
public void setType(String type) {
this.type = type;
}
}
That way your class does not have a different set of fields based on some runtime state. If runtime state is driving what fields your class contains, you're not much better off than with just a Map.
If you can't change that, you're left with custom serialization.

Simple LINQ to SQL extension method

How would I write a simple LINQ to SQL extension method called "IsActive" which would contain a few basic criteria checks of a few different fields, so that I could reuse this "IsActive" logic all over the place without duplicating the logic.
For example, I would like to be able to do something like this:
return db.Listings.Where(x => x.IsActive())
And IsActive would be something like:
public bool IsActive(Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
Otherwise, I am going to have to duplicate the same old where criteria in a million different queries right throughout my system.
Note: method must render in SQL..
Good question, there is a clear need to be able to define a re-useable filtering expression to avoid redundantly specifying logic in disparate queries.
This method will generate a filter you can pass to the Where method.
public Expression<Func<Listing, bool>> GetActiveFilter()
{
return someListing => someListing.Approved && !someListing.Deleted;
}
Then later, call it by:
Expression<Func<Filter, bool>> filter = GetActiveFilter()
return db.Listings.Where(filter);
Since an Expression<Func<T, bool>> is used, there will be no problem translating to sql.
Here's an extra way to do this:
public static IQueryable<Filter> FilterToActive(this IQueryable<Filter> source)
{
var filter = GetActiveFilter()
return source.Where(filter);
}
Then later,
return db.Listings.FilterToActive();
You can use a partial class to achieve this.
In a new file place the following:
namespace Namespace.Of.Your.Linq.Classes
{
public partial class Listing
{
public bool IsActive()
{
if(this.Approved==true && this.Deleted==false)
return true;
else
return false;
}
}
}
Since the Listing object (x in your lambda) is just an object, and Linq to SQL defines the generated classes as partial, you can add functionality (properties, methods, etc) to the generated classes using partial classes.
I don't believe the above will be rendered into the SQL query. If you want to do all the logic in the SQL Query, I would recommend making a method that calls the where method and just calling that when necessary.
EDIT
Example:
public static class DataManager
{
public static IEnumerable<Listing> GetActiveListings()
{
using (MyLinqToSqlDataContext ctx = new MyLinqToSqlDataContext())
{
return ctx.Listings.Where(x => x.Approved && !x.Deleted);
}
}
}
Now, whenever you want to get all the Active Listings, just call DataManager.GetActiveListings()
public static class ExtensionMethods
{
public static bool IsActive( this Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
}
Late to the party here, but yet another way to do it that I use is:
public static IQueryable<Listing> GetActiveListings(IQueryable<Listing> listings)
{
return listings.Where(x => x.Approved && !x.Deleted);
}
and then
var activeListings = GetActiveListings(ctx.Listings);

How to determine lazy-loaded properties at runtime on a linq table?

I am iterating over the properties of various mapped tables in my code and need to know whether or not each property is lazy loaded. I have found that the instance variable used for storage, denoted by the Storage attribute on the property, will be of type System.Data.Linq.Link.
Is there a way that I can leverage these two facts at runtime to solve this problem?
Code:
public void LazyLoad(Type tableType)
{
foreach (var prop in tableType.GetGenericArguments()[0].GetProperties())
{
if (/* IS LAZY LOADED */)
{
//real work here...
Console.WriteLine(prop.Name);
}
}
}
The mappings look like this:
public partial class Address
{
private System.Data.Linq.Link<string> _City;
[Column(Storage="_City", DbType="...")]
public string City
{
get { /* ... */ }
set { /* ... */ }
}
}
You are almost there. Just a spoon full of reflection helps the medicine go down ;-)
private static bool IsLazyLoadedProperty(PropertyInfo property)
{
var column = property.GetCustomAttributes(typeof(ColumnAttribute), true)[0]
as ColumnAttribute;
var field = property.DeclaringType.GetField(column.Storage,
BindingFlags.Instance | BindingFlags.NonPublic);
if (!field.FieldType.IsGenericType)
{
return false;
}
return field.FieldType.GetGenericTypeDefinition() == typeof(Link<>);
}

Can you explain this thing about encapsulation?

In response to What is your longest-held programming assumption that turned out to be incorrect? question, one of the wrong assumptions was:
That private member variables were
private to the instance and not the
class.
(Link)
I couldn't catch what he's talking about, can anyone explain what is the wrong/right about that with an example?
public class Example {
private int a;
public int getOtherA(Example other) {
return other.a;
}
}
Like this. As you can see private doesn't protect the instance member from being accessed by another instance.
BTW, this is not all bad as long as you are a bit careful.
If private wouldn't work like in the above example, it would be cumbersome to write equals() and other such methods.
Here's the equivalent of Michael Borgwardt's answer for when you are not able to access the private fields of the other object:
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return other.valueEquals(this.value); // <------------
}
#Override // This method would probably also be declared in an interface
public boolean valueEquals(int oValue) {
return this.value == oValue;
}
}
Nowadays this is familiar to Ruby programmers but I have been doing this in Java for a while. I prefer not to rely on access to another object's private fields. Remember that the other object may belong to a subclass, which could store the value in a different object field, or in a file or database etc.
Example code (Java):
public class MutableInteger {
private int value;
// Lots of stuff goes here
public boolean equals(Object o) {
if(!(o instanceof MutableInteger)){ return false; }
MutableInteger other = (MutableInteger) o;
return this.value == other.value; // <------------
}
}
If the assumption "private member variables are private to the instance" were correct, the marked line would cause a compiler error, because the other.value field is private and part of a different object than the one whose equals() method is being called.
But since in Java (and most other languages that have the visibility concept) private visibility is per-class, access to the field is allowed to all code of the MutableInteger, irrelevant of what instance was used to invoke it.