Fortis-Collection / fortis

A framework for creating a strongly typed model based on Sitecore templates and the Sitecore API

Home Page:http://fortis.ws

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

IntegerFieldWrapper can cause null exceptions

mikaelnet opened this issue · comments

In IntegerFieldWrapper, the Value property can cause null exception, since all execution paths doesn't ensure _value has has a value and at the end it returns _value.Value. Suggest returning something like _value != null ? _value.Value : default(long)

I'm not sure what Richard intended on saying but at least we got some info on his phone :)! This is an interesting issue because it depends on how you look at it. The problem resides with the fact you can enter an empty string into an integer field in Sitecore. The question becomes what should happen if the field is empty?

My thought is to, as you mention, return the default long which will be 0. I can also see a need for knowing whether the field is actually set. You wouldn't know if the editor has entered 0 as the value or it's come back because it's empty. I'd probably introduce a new HasValue property (perhaps to all fields) which can be used to check if something has been entered.

Hmm - not sure how my phone replied to this either! I agree with Jason tho, we would need a way of knowing that the user has not set the field. I normally check string.IsNullOrWhiteSpace on the .RawValue for that. But a dedicated property would be clearer.

Yes, I agree. I also typically perform an IsNullOrWhiteSpace check on the .RawValue field, but it's easy to forget and some otherwise elegant code can become quite cluttered. Also, since Sitecore stores everything as strings, there could potentially be other characters in a field as well, making long.TryParse() return false dispite IsNullOrWhiteSpace is false.

I'd really like a property like HasValue in IFieldWrapper as well. I've missed it in other areas as well. However, we might consider an alternative name for it, so it's not mixed with Sitecore.Data.Fields.Field.HasValue that works slightly different.

Normally Sitecore validates fields like Number or Integer so you can't insert other charachters than digits (except you're messing with raw values or that validation is disabled on your setup). Agree about having HasValue in the base class, but its implmentation could be different for fields like Image or Link. They store xml and sometimes .RawValue could be not empty but xml won't reffer to any item or image. In result we may get exception. I vote for adding "smart" .HasValue property that makes sure those specific field types are linked to existing items.

Added the HasValue property as suggested by @vhil

nice!