How do you deal with structured strings?

Suppose I have an object representing a person with getter and setter methods for the person’s email address. The setter method definition might look something like this:

setEmailAddress(String emailAddress)
    {
    this.emailAddress = emailAddress;
    }

The call person.setEmailAddress(0)then generates a type error, but the call person.setEmailAddress("asdf")will not - even if "asdf" is in no way a valid email address.

In my experience, so-called strings are almost never arbitrary sequences of characters without limitation of length or format. URIs come to mind - like street addresses, like phone numbers, as well as names ... you get the idea. However, these data types are most often stored as "just strings."

Returning to the object of my face, suppose I change setEmailAddress()so

setEmailAddress(EmailAddress emailAddress)
    // ...

where EmailAddressis the class ... whose constructor takes a string representation of the email address. Did I get anything?

OK, so the email address is an unfriendly example. What about the URI class, which takes a string representation of a URI as a constructor parameter and provides methods for managing this URI - setting the path, fetching the request parameter, etc. The importance of the source line becomes important.

So, I ask all of you, how do you deal with strings that have structure? And how do you clearly define your structural expectations in your interfaces?

Thanks.

+5
source share
9

!

, . , . , , , .

, , . , , , " " ( ), " " ( ). URL- google 'regex', , :

, "", , , : \ b [A-Z0-9._% + -] + @[A-Z0-9.-]+. [A-Z] {2,4}\b RegexBuddy. , , . , , , , .

, , , . URL- , URL.

, , - ( Microsoft , , ). " ".

, . , , . , . , , , , , , - , . , , , , . , .

, , / .. , - , , , . , , .

, - , .

+2

" " "" ".

, . - - , .

+9
+2

- . , , , , . .

+1

- , . , , . .

struct EMail
{
    String BeforeAt = "johndoe123";
    String AfterAt = "gmail.com";
}

Struct URL
{
    String Protocol = "http";
    String Domain = "sub.example.com";
    String Path = "stuff/example.html";
}
+1

, EmailAddress, , , EmailAddress . factory " ", .

0

, , , . , , - "" , ​​ EmailAddressFromString(String), EmailAddress ( , ) m .

, , Joel http://www.joelonsoftware.com/articles/Wrong.html, .

0

, , , : .

: . , , . , , . , , "bob" "bob@gmail.com". , null.

, , - , . , , , . , EmailAddress , , "EmailHelper" .

0

, , EmailAddress , .

, - :

EmailAddress(String email)

SetEmailAddress(String email)

In both cases, you will need to verify the input of the email string, which will return you to the original validation problem.

I would like, as others have pointed out, to use regular expressions.

Having the EmailAddress class would be useful if you plan to later perform certain operations on your stored information (for example, get only a domain name, for example, like that).

0
source

All Articles