I have a number of methods that can return a string, bool, int or a tuple<int,bool> or if the method fails, returns a class with a numnber of properties in it detailing the in and out params.
Is there a way that when the call returns that I can avoid using Reflection to determine the return types and the values? The code is for low end mobile devices using Xamarin (so both iOS and Android)
No there's no way to traverse through the class properties without reflection.
But As a last resort, you can override the class ToString() method and manually return what you want to return. But you need to be careful as the every time you edit your class you need to update ToString()
Related
Suppose we have some data classes which are generated with protoc.
Google's toString() sucks for multiple reasons, it's not very human-readable, and even puts line breaks in representation which screws up logs and many tools that don't expect multiline log.
So the problem is: how do we redefine custom toString() for a class like that?
I've tried to override (or maybe hide?) original toString() with an extension function like this
fun Messages.DataClass.toString(): String {
return "some custom logic"
}
but it won't pick up the extended function.
It's not possible to change the implementation of an existing method in a class using Kotlin. An instance method defined in a class always takes priority over an extension function with the same signature.
I'm working on a ASP.NET MVC system where you may click on a ajax link that will open a window (kendo window but it does not affect the situation) which a complex flow. To make this less of a nightmare to manage, I made a ViewModel (as I should) but this ViewModel is a complex object due to the complexity of the procedure.
There is anywhere from a single to 5 windows that asks various questions depending on a lot of conditions (including, but not limited to, what time you click the link, who you are, what schedule is attached to your account and, obviously, your previous answers in this flow).
The problem is that having a complex object, I cannot simply make #Html.HiddenFor(o=>o.XXX). So I proceeded to find an alternative and it led me with a single option, TempData. I'm really not a fan of dynamics and object types. I'd really like to have this View Model strongly typed.
What would be the best way to approach this?
Here is a case where using Session or TempData might make sense. Contrary to popular belief, you can make these somewhat strongly-typed. Not like a viewmodel, but you can avoid keychain messes by using extension methods.
For example, instead of doing something like this:
TempData["NestedVariable1"] = someObject;
...
var someObject = TempData["NestedVariable1"] as CustomType;
You can write extension methods to store these variables, and encapsulate the keys and casting in the extension methods.
public static class ComplexFlowExtensions
{
private static string Nv1Key = "temp_data_key";
public static void NestedVariable1(this TempData tempData, CustomType value)
{
// write the value to temp data
tempData[Nv1Key] = value;
}
public static CustomType NestedVariable1(this TempData tempData)
{
// read the value from temp data
return tempData[Nv1Key] as CustomType;
}
}
You can then read / write these values from either controllers or views like this:
TempData.NestedVariable1(someObject);
...
var someObject = TempData.NestedVariable1();
You could use the same pattern with Session as well. And instead of saving each individual scalar value in a separate variable, you should be able to store an entire nested object graph in the variable. Either that, or serialize it to JSON and store that, then deserialize when you get it back out. Either way, I think this beats a ton of hidden fields written out to your view's form.
I want to have a class that has a number of fields such as String, Boolean, etc and when the class is constructed I want to have a fieldname associated with each field and verify the field (using regex for strings). Ideally I would just like specify in the constructor that the parameter needs to meet certain criteria.
Some sample code of how :
case class Data(val name: String ..., val fileName: String ...) {
name.verify
// Access fieldName associated with the name parameter.
println(name.fieldName) // "Name"
println(fileName.fieldName) // "File Name"
}
val x = Data("testName", "testFile")
// Treat name as if it was just a string field in Data
x.name // Is of type string, does not expose fieldName, etc
Is there an elegant way to achieve this?
EDIT:
I don't think I have been able to get across clearly what I am after.
I have a class with a number of string parameters. Each of those parameters needs to validated in a specific way and I also want to have a string fieldName associated with each parameter. However, I want to still be able to treat the parameter as if it was just a normal string (see the example).
I could code the logic into Data and as an apply method of the Data companion object for each parameter, but I was hoping to have something more generic.
Putting logic (such as parameter validation) in constructors is dubious. Throwing exceptions from constructors is doubly so.
Usually this kind of creational pattern is best served with one or more factory methods or a builder of some sort.
For a basic factory, just define a companion with the factory methods you want. If you want the same short-hand construction notation (new-free) you can overload the predefined apply (though you may not replace the one whose signature matches the case class constructor exactly).
If you want to spare your client code the messiness of dealing with exceptions when validation fails, you can return Option[Data] or Either[ErrorIndication, Data] instead. Or you can go with ScalaZ's Validation, which I'm going to arbitrarily declare to be beyond the scope of this answer ('cause I'm not sufficiently familiar with it...)
However, you cannot have instances that differ in what properties they present. Not even subclasses can subtract from the public API. If you need to be able to do that, you'll need a more elaborate construct such as a trait for the common parts and separate case classes for the variants and / or extensions.
I have two fields and I need to generate an attribute, using Microsoft Enterprise Library validation, so that either or has to have a value, but both can not be null at the same time.
Use a custom validator.
[HasSelfValidation]
public class ValidateMe {
[SelfValidation]
public void ValidateFieldNotNul(ValidationResults validationResults)
{
.. start psudo code
if( xor)
validationResults.AddResult( new ValidationResult("One must not be null",...));
}
}
The Validation Application Block has a PropertyComparisonValidator which will let you compare one property with another. Unfortunately, this validator only allows a ComparisonType of: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual so this doesn't actually help you.
I think you have 2 options:
Self Validation
Custom Validator
Self Validation (shown by #Nix) is probably the easiest but would require this to be reimplemented for every scenario where you have that requirement (at least to put the hooks to call a common method).
Creating a custom validator would result in code that could be added to the configuration or attributed directly on entities and that could easily be reused.
A custom validator will definitely be more work but may be worth it if you need the reuse (it can be reused across applications, for example) or prefer that design.
Is it possible at all to create eventlisteners (i.e. when the value changes) for a variable of type string, int, bool, etc.?
I haven't seen this in any programming language so far, except for some Collections (like ArrayCollection in Flex), which use events to detect changes in the collection.
If not possible at all, why not? What's the reason for this? Are there any best practices to achieve the same sort of functionality? And what about extending functionality with databinding?
I don't think there is anything by default, however, you can create a custom event and raise it on the set of the method. Something like...
C# example
public delegate void MyValueChangedEventHandler(bool oldValue, bool newValue);
public event MyValueChangedEventHandler MyValueChanged;
private bool myValue;
...
public bool MyValue
{
get { return myValue; }
set
{
if (myValue != value)
{
var old = myValue;
myValue = value;
MyValueChanged(old, myValue);
}
}
}
I guess this sort of functionality is not added in any framework/runtime since it would create a big overhead (think on how many times you modify a variable holding a primitive type within the average application) while being not used under normal circunstances.
Anyway, in .NET at least (and I guess that in other OO environments as well), you can define properties, which are accessed as normal variables but can have associated code that reacts when its value is read or modified.
It is possible if you wrap your variables in getters and setters and fire the event when the setter is called.
How about using setter methods and having them register events when changing the value of the variable?
In general, no. The reason is that primitive types are simply bits and bytes stored in some memory location: changing the data in that memory location does just that, and nothing else. Firing events would require calling some methods/functions. So the functionality can be achieved by wrapping the primitive types in some kind of wrapper objects - but of course, they're not 100 % interchangeable: for instance Java's primitive wrapper types (Integer etc.) are marked final, so it's not possible to extend them with event-firing versions to take advantage of auto(un)boxing.
Another approach is to poll the variable frequently and fire appropriate events if it has changed. This is a "dirty" approach with obvious disadvantages (performance overhead, not immediate reaction), but could regardless be useful in some situations. If you do this from another thread in Java, be sure to mark the variable volatile.
It is possible to create listeners, as some of ther others have mentioned, by making a class that fires an event whenever a property changes. This is obviously a lot less efficient than just assigning a value, but there are cases where it could be useful.
Some languages (VB6 and some others) have the ability in debug mode to stop execution when the value of a variable changes. I haven't seen this in .net, but it's liable to be in there somewhere. :-)
It seems to me that using an event to signal a simple variable change could be accomplished with if statements at each assignment, unless the value that variable is being changed externally, in which case you could use a class to handle it.