Is there any concern about returning generic type object in Dart? - oop

I want to implement a different error handling approach in a project without chaining exceptions.
To make it simple as possible, I am tend to write my own basic either-like model.
class Either<F, T> {
final F failure;
final T value;
const Either(this.failure, this.value);
Object check (){
if (failure != null) return failure;
return value;
}
}
I am concerning about returning the type Object, is there any problem or considerations with that in Dart or any other language?
Edit:
or returning dynamic type...
dynamic check(){
if (failure != null) return failure;
return value;
}

I think in your case, it's kind of a wired implementation. The question is, what do you want to do with the actual implementation ? Do you want to replace an if else that will appear over and over? In that case, what would you do if you have to handle the error (failure) ? I think a better approach is to use functions as parameters. Here's a short suggestion.
class Either<T, F> {
T value;
F fail;
Either(this.value, this.fail);
void check(success(T value), {failure(F fail)}) {
if (fail != null && failure != null) {
failure(fail);
} else if (value != null) {
success(value);
}
}
}
class SomeClass {
void checkTheImplementation() {
Either<String, Error> maybeString = Either("testing", null);
// if you don't want to handle the error.
maybeString.check((value) => print(value));
// if you want to handle the error
maybeString.check((value) => print(value), failure: (err) {
print(err.toString());
});
}
}

I have looked over and decided to go with baihu92's either_type way. It's much more clear and comprehensible than either in the dartz package. Here is my implementation:
and the usage is like:

Related

In Objective C, what happens if we pass nil or null to #synchronized() block?

Usually we will pass an object to #synchronized() block for unique reference. for example,
+(id)sharedDBHandler
{
#synchronized (self) {
if (sDBHandler == nil) {
sDBHandler = [self new];
}
}
return sDBHandler;
}
what happens if we pass nil to it?
It doesn't #synchronize() at all. No locks taken. No-op. Undefined behavior.
Perfectly valid question, btw, regardless of whether the code is antiquated and no longer the correct means of generating a singleton.
From the github repository. While not a documented claim, breaking this policy would cause compatibility hell.
int objc_sync_enter(id obj)
{
int result = OBJC_SYNC_SUCCESS;
if (obj) {
SyncData* data = id2data(obj, ACQUIRE);
assert(data);
data->mutex.lock();
} else {
// #synchronized(nil) does nothing
if (DebugNilSync) {
_objc_inform("NIL SYNC DEBUG: #synchronized(nil); set a breakpoint on objc_sync_nil to debug");
}
objc_sync_nil();
}
return result;
}
Where:
BREAKPOINT_FUNCTION(
void objc_sync_nil(void)
);

Throwing on unwrapping nil optional

Consider the following code:
enum MyErrorType:ErrorType {
case BadTimes
}
var mightHaveAValue: String?
do {
if let value = mightHaveAValue {
// do stuff with value
} else {
throw MyErrorType.BadTimes
}
// do stuff with NSFileManager using mightHaveAValue which might throw
} catch {
// handle error
}
...in which I have a large do/try/catch block. In this instance the error handling will be the same, whether mightHaveAValue is empty or something bad happens with NSFileManager later on. So it makes sense to re-use the error handling code.
Is this the cleanest approach going in Swift2, or is there some way I can automatically throw/catch on unwrapping an optional with no value?
It looks ok, but it's even better with guard let instead of if let because it lets you use the unwrapped value in the main do block instead of having to work inside an if let branch. You can also use several catch branches to handle different error types.
do {
guard let value = mightHaveAValue else {
throw MyErrorType.BadTimes
}
// do stuff with value
} catch let error as MyErrorType {
// handle custom error
} catch let error as NSError {
// handle generic NSError
}
There is no automatic way to handle unwrapping optionals, you have to use one of the many known ways: if let, guard let, nil coalescing, etc.
Maybe just use an extension like this 🤔
extension Optional {
func throwing() throws -> Wrapped {
if let wrapped = self {
return wrapped
} else {
throw NSError("Trying to access non existing value")
}
}
}

Return Value from Function Swift

I know this is probably a simple queston, I would like to return the value of currentLocGeoPoint and return the array of Objects which is of type PFObject.
Tried to save it as a global variable, but it doesn't work because it is asynchronous and doesn't take a value yet. Returns empty.
Tried to return currentLocGeoPoint and changed Void in to PFGeoPoint in. Gives error: PFGeoPoint is not convertible to 'Void'
So I'm not sure how I can fetch the variable currentLocGeoPoint.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("Error:" + error.localizedDescription)
//return
}
if placemarks.count > 0 {
let pm = placemarks[0] as CLPlacemark
self.displayLocationInfo(pm)
currentLoc = manager.location
currentLocGeoPoint = PFGeoPoint(location:currentLoc)
var query = PFQuery(className:"Bar")
query.whereKey("BarLocation", nearGeoPoint:currentLocGeoPoint, withinMiles:10)
query.limit = 500
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if objects != nil {
} else {
println("error: \(error)")
}
}
} else {
println("error: \(error)")
}
})
}
I don't understand the notion of "I want to return currentLocGeoPoint". Return it to what? You're in a CLLocationManagerDelegate method, so there's no one to return it to.
What you could do, though, is, when the request is done (i.e. within this closure), call some other function that needed the currentLocGeoPoint. Or you could update the UI to reflect the updated information (make sure to dispatch that update to the main thread, though). Or, if you have other view controllers or model objects that need to know about the new data, you might post a notification, letting them know that there is an updated currentLocGeoPoint. But within this method, there's no one to whom you would "return" the data.
You could assign it to a stored property of your class. Just use
self.<property> = currentLocGeoPoint

Callee taking action based on type of caller

I would like to know if there is some alternate better pattern other than below where an object passes itself as a context to another object which in turn uses the context or lack as logic to build the necessary output. I have tried making the caller/sender an interface and pass itself as an interface but the real question is is it good practice for the called object to even know who its caller is, i.e. to distinguish it from other callers and take separate actions if necessary? Am I missing a piece to the puzzle?
Caller (CGQuery):
public string RenderForLoop()
{
...
sb.Append(string.Join("",this.ContentIsCGExpressions.Select(exp => exp.GetProcessedExpression(this))));
...
Callee (CGExpression):
public string GetProcessedExpression(object context = null)
{
...
retv = ReplaceCodes(retv, context);
...
private string ReplaceCodes(string retv, object context = null)
{
... retv = ReplaceContextSequenceCode(retv, context);
return retv;
}
...
private string ReplaceContextSequenceCode(string retv, object context = null)
{
var _regx = new Regex("(?i)<q_ctx_seq>");
var _matchresult = _regx.Match(retv);
while (_matchresult.Success)
{
string replacement = FetchContextSequenceQueryTableFieldExpression(context);
retv = retv.Replace(_matchresult.Groups[0].Value, replacement);
_matchresult = _matchresult.NextMatch();
}
return retv;
}
private string FetchContextSequenceQueryTableFieldExpression(object context = null)
{
if (context != null && context is CGQuery)
{
return ((CGQuery)context).FetchContextSequenceQueryTableFieldExpression();
}
return this.CGStatementsUsedAsParamsFor.Any() ?
this.CGStatementsUsedAsParamsFor.Single().FetchContextSequenceQueryTableFieldExpression(context)
:
this.CGQueriesContentFor.Single().FetchContextSequenceQueryTableFieldExpression();
}
It's this line in the above that I'm concerned about (seems to violate encapsulation?)
if (context != null && context is CGQuery)
{
return ((CGQuery)context).FetchContextSequenceQueryTableFieldExpression();
}
sorry I don't know how to highlight the code in the main block.
What about letting the caller deliver an object to the callee containing the action to execute? The caller may be queried within this action without the callee being aware of its existence.
Generally I would say it's not good OOP practice to decide behaviour on the class of the calling object.

Wiring up WCF client side caching?

My application uses client side enterprise caching; I would like to avoid writing code for each and every cacheable call and wondered if there is a solution such that WCF client side calls can be cached, even for async calls.
Can this be done with WCF "behaviour" or some other means? Code examples?
I did this the other day with Generic Extension methods on the WCF service client (DataServiceClient). It uses Actions and Funcs to pass around the actual ServiceClient calls. The final client usage syntax is a little funky (if you don't like lambdas), but this method does FaultException/Abort wrapping AND caching:
public static class ProxyWrapper
{
// start with a void wrapper, no parameters
public static void Wrap(this DataServiceClient _svc, Action operation)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke();
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
}
// next, a void wrapper with one generic parameter
public static void Wrap<T>(this DataServiceClient _svc, Action<T> operation, T p1)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
}
// non-void wrappers also work, but take Func instead of Action
public static TResult Wrap<T, TResult>(this DataServiceClient _svc, Func<T, TResult> operation, T p1)
{
TResult result = default(TResult);
bool success = false;
try
{
_svc.Open();
result = operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
return result;
}
}
On the client side, we have to call them like this:
internal static DBUser GetUserData(User u)
{
DataServiceClient _svc = new DataServiceClient();
Func<int, DBUser> fun = (x) => _svc.GetUserById(x);
return _svc.Wrap<int, DBUser>(fun, u.UserId);
}
See the plan here? Now that we have a generic set of wrappers for WCF calls, we can use the same idea to inject some cacheing. I went "low tech" here, and just started throwing around strings for the cache key name... You could do something more elegant with reflection, no doubt.
public static TResult Cache<TResult>(this DataServiceClient _svc, string key, Func<TResult> operation)
{
TResult result = (TResult)HttpRuntime.Cache.Get(key);
if (result != null)
return result;
bool success = false;
try
{
_svc.Open();
result = operation.Invoke();
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
HttpRuntime.Cache.Insert(key, result);
return result;
}
// uncaching is just as easy
public static void Uncache<T>(this DataServiceClient _svc, string key, Action<T> operation, T p1)
{
bool success = false;
try
{
_svc.Open();
operation.Invoke(p1);
_svc.Close();
success = true;
}
finally
{
if (!success)
_svc.Abort();
}
HttpRuntime.Cache.Remove(key);
}
Now just call Cache on your Reads and Uncache on your Create/Update/Deletes:
// note the parameterless lambda? this was the only tricky part.
public static IEnumerable<DBUser> GetAllDBUsers()
{
DataServiceClient _svc = new DataServiceClient();
Func<DBUser[]> fun = () => _svc.GetAllUsers();
return _svc.Cache<DBUser[]>("AllUsers", fun);
}
I like this method because I didn't have to recode anything server-side, just my WCF proxy calls (which were admittedly a little brittle / smelly to have scattered about everywhere).
Substitute in your own WCF proxy conventions and standard caching procedures, and you're good to go. It's a lot of work to create all the generic wrapper templates at first too, but i only went up to two parameters and it helps all my caching operations share a single function signature (for now). Let me know if this works for you or if you have any improvements.
Unfortunately, I think you'll have to roll your own. I don't believe WCF has a client-side caching mechanism built in.
The answer to this question may also help.
Similar to the above solution, check out http://www.acorns.com.au/blog/?p=85 (PolicyInjection on WCF Services). You can sepecify the policy to match your service name.
If you want caching without having to explicitly implement it on each and every service call, consider the Caching Handler in the Policy Injection application block. You can mark your calls with an attribute, and the policy injection block will handle caching for you.
http://msdn.microsoft.com/en-us/library/cc511757.aspx